函数
func 函数名(形参列表)->返回值{
函数体
}
- 可变参数 在参数类型后面加… ,可接受多个参数值
- 默认参数 直接在形参赋值
- 可变参数放在最后面,默认参数放在次后面
- 传递的只是参数的值,而非指针,如需传递指针,则需使用inout 强制传递指针。
- 函数类型:(Int,Int)->Int 举例如下:
func squre(num:Int) -> Int{
return num*num;
}
func cube(num:Int) -> Int{
return num*num*num;
}
func getmathFunc(Type type: String) ->(Int) ->Int {
if(type == "squre"){
return squre;
}else {
return cube;
}
}
var mathFunc = getmathFunc(Type: "other")
print(mathFunc(5))
函数同样可以重载,这跟其他语言一样。
包
{(形参列表)->返回值类型 in
可执行语句
}
相当于object-c 中的block,c# 的表达式
func getMathType(Type type:String)->(Int)->Int {
func squre(num:Int)->Int {
return num*num
}
func cube(num:Int)->Int {
return num*num*num
}
switch type {
case "squre":
return {(num:Int)->Int in
return num*num
}
default:
return {(num:Int)->Int in
return num*num*num
}
}
}
var mathType = getMathType(Type: "squre")
print(mathType(5))
利用上下文可以推断类型时
var squre:(Int) -> Int = {(num:Int)->Int in return num*num}
print(squre(3))
也可以省略形参名,直接用$0,$1....
来表示第几个参数:
var squre:(Int) -> Int = {$0 * $0}
print(squre(3))
尾随闭包
func someFunction(num:Int ,fn:(Int)->()) {
//执行代码
}
someFunction(20,{})
someFunction(20){}