Functions can be used as a type, as a type without distinction from other data types:
There are 3 definitions of the following functions:
(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")
}
The return type of the first and second functions is (double,double), Double, and the third function returns the type (), ()
The function is used as a parameter type: You can use the type of the function as the return type of another function:
Example:
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))")
You can use function types as parameter types for other functions:
Example:
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,double), double, a:double,b:double), double {
var area = Funname (A, B)
Return area
}
var result:D ouble = Getareabyfunc (rectanglearea,20,30)
This article is from the "Ordinary Road" blog, please be sure to keep this source http://linjohn.blog.51cto.com/1026193/1620360
Swift function type