函数可以作为一种类型使用,作为类型与其它数据类型没有区别:
有如下3个函数的定义:
(1)func rectangleArea(width : Double,height : Double ) -> Double {
let area = width * height
return area
}
(2)func triangleArea(bottom : Double,height : Double ) -> Double {
let area = 0.5 * bottom * height
return area
}
(3)func sayHello(){
println("Hello World")
}
第一个和第二个函数的返回类型都是(Double,Double) -> Double,第三个函数返回的类型为() ->()
函数作为参数类型使用:可以把函数的类型作为另一个函数的返回类型使用:
示例:
func rectangleArea(width : Double,height : Double ) -> Double {
let area = width * height
return area
}
func triangleArea(bottom : Double,height : Double ) -> Double {
let area = 0.5 * bottom * height
return area
}
func getArea(type : String) -> (Double,Double) ->Double {
var returnFunction :(Double,Double) -> Double
switch type {
case "rect":
returnFunction = rectangleArea
case "tria" :
return triangleArea
default:
returnFunction = rectangleArea
}
return returnFunction
}
var area = getArea("tria")
println("TriangleArea:\(area(20,30))")
var area = getArea("rect")
println("TriangleArea:\(area(20,30))")
示例:
func rectangleArea(width : Double,height : Double ) -> Double {
let area = width * height
return area
}
func triangleArea(bottom : Double,height : Double ) -> Double {
let area = 0.5 * bottom * height
return area
}
func getAreaByFunc(funcName : (Double,a: Double,b: Double) -> Double {
var area = funName(a,b)
return area
}
var result :Double = getAreaByFunc(rectangleArea,20,30)
原文链接:https://www.f2er.com/swift/327506.html