Swift中的闭包定义

2019-06-26  本文已影响0人  成都老刘

定义闭包变量

 var closureName: (ParameterTypes) -> (ReturnType) 

定义可选闭包变量

 var closureName: ((ParameterTypes) -> (ReturnType))? 

定义闭包别名

 typealias ClosureType = (ParameterTypes) -> (ReturnType) 

定义闭包常量

 let closureName: ClosureType = { ... } 

在函数内部

 funcName({(ParameterTypes) -> (ReturnType) in statements}) 

作为函数参数

 array.sort({ (item1: Int, item2: Int) -> Bool in return item1 < item2 }) 

作为函数参数(隐式参数类型)

 array.sort({ (item1, item2) -> Bool in return item1 < item2 }) 

作为函数参数(隐式参数类型、隐式返回类型)

 array.sort({ (item1, item2) in return item1 < item2 }) 

作为函数最后的参数

 array.sort { (item1, item2) in return item1 < item2 } 

作为函数最后的参数(使用简略参数命名方式)

 array.sort { return $0 < $1 } 

作为函数最后的参数(隐式返回值)

 array.sort { $0 < $1 } 

作为函数最后的参数(as a reference to an existing function)

 array.sort(<) 
上一篇 下一篇

猜你喜欢

热点阅读