//: Playground - noun: a place where people can play
import UIKit
///
//
//func sorted(isOrderedBefore:(T, T)->Bool) -> [T]{
//
//}
let animals = ["fish", "cat", "chicken", "dog"]
//func isOrderedBefore(one : String, two: String) -> Bool
//{
// return one < two
//}
//
//let sortedString = animals.sort(isOrderedBefore)
// 与排序 小于号 ,传递核心代码
let sortedString = animals.sort({(one: String, two: String) -> Bool in
return one < two
})
// 在sort 函数里面传递了参数 而参数又是一个函数 ,这个函数就叫做闭包
// 闭包 没有完整的函数声明 有参数列表 one: String, two: String
// in关键字后面是闭包的实现代码
// 编译器可以断言出参数的类型
let sortedString2 = animals.sort({(one, two) -> Bool in
return one < two
})
// -> Bool 返回值信息也可以 删除掉 这个信息可以再sort的声明中得到< sort 声明>
let sortedString3 = animals.sort({(one, two) in
return one < two
})
// 没有返回值类型->bool声明以后 ()也可以去除掉
let sortedString4 = animals.sort({one, two in
return one < two
})
// 可以省略执行代码的return语句 编译器已经断言出来返回值是bool 类型
//所执行代码一行,删除return 语句
let sortedString5 = animals.sort({one, two in
one < two
})
//接下来我们还可以省略参数
// one two 没有意义 用参数本地常量进行代替
let sortedString6 = animals.sort({$0 < $1})
//如果传递的闭包是方法或者函数的最后一个参数, 可以将闭包放到闭包的外面
//称为结尾闭包
let sortedString7 = animals.sort(){$0 < $1}
print(sortedString7)
// 还可以移除没有参数的括号
let sortedString8 = animals.sort{$0 < $1}
print(sortedString8)
//把花括号替换为小括号 只写一个 < 闭包神奇之处
let sortedString9 = animals.sort(>)
print(sortedString9)
//----------------------------------------------
//闭包还可以捕获 上下文中常量或者变量的数值
//甚至原始环境销毁也可以使用
typealias stateMachineType = () ->Int
func makeStateMachine(maxState: Int) -> stateMachineType{
var currentState: Int = 0
return{
currentState++
if currentState > maxState{
currentState = 0
}
return currentState
}
}
let tt = makeStateMachine(2)
print(tt())
print(tt())
print(tt())
print(tt())
print(tt())
// 不管makeStateMachine 是否在生存期内 都可以捕获makeStateMachine里面的 currentState 变量值 一直存在
//闭包可以超越自身的生命周期捕获外面的变量值
swift 闭包 由浅入深 优化
最新推荐文章于 2017-08-31 17:11:54 发布