func printIfTrue(predicate: ()-> Bool){
if predicate(){
print("the result is true")
}
}
//1直接调用方法
printIfTrue { () -> Bool in
return 2 > 1
}
//2闭包在圆括号内
printIfTrue({ return 2 > 1 })
//3:使用尾部闭包方式,闭包体在圆括号之外
printIfTrue(){ return 2 > 1 }
//4:在 Swift 中对闭包的用法可以进行一些简化,在这种情况下我们可以省略掉 return,写成:
printIfTrue({ 2 > 1})
//5:还可以更近一步,因为这个闭包是最后一个参数,所以可以使用尾随闭包 (trailing closure) 的方式把大括号拿出来,然后省略括号,变成:
printIfTrue{2 > 1}
func printIfTrue(@autoclosure predicate: ()-> Bool){
if predicate(){
print("the result is true")
}
}
printIfTrue(2 > 1)
//直接进行调用了,Swift 将会把 2 > 1 这个表达式自动转换为 () -> Bool。这样我们就得到了一个写法简单,表意清楚的式子。
func printInformation(@autoclosure predicate1: ()-> Bool,@autoclosure predicate2: ()-> Bool){
if predicate1() && predicate2(){
print("the result is true")
}else{
print("the result is false")
}
}
printInformation( 3 > 2, predicate2: 4 > 1)
func executeAsyncOp(asyncClosure: () -> ()) -> Void {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
asyncClosure()
}
}
func executeAsyncOp(@noescape asyncClosure: () -> ()) -> Void {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
asyncClosure()
}
}
error:closure use of @noescape parameter 'asyncClosure' may allow it to escape asyncClosure()
func map(@noescape transform: (Self.Generator.Element) -> T) -> [T]
func filter(@noescape includeElement: (Self.Generator.Element) -> Bool) -> [Self.Generator.Element]
func reduce(initial: T, @noescape combine: (T, Self.Generator.Element) -> T) -> T
func doWork(closure: () -> ()) {
closure()
print("end")
}
doWork {
print("doWork")
}
//doWork
//end
func doWorkAsync(closure: @escaping () -> ()) {
DispatchQueue.main.async {
closure()
}
print("end")
}
doWorkAsync {
print("doWork")
}
//end
//doWork
class Person {
var name = "Jack"
func method1() {
doWork {
print("name = \(name)")
}
name = "Rose"
}
func method2() {
doWorkAsync {
print("name = \(self.name)")
}
name = "Rose"
}
func method3() {
doWorkAsync { [weak self] in
print("name = \(String(describing: self?.name))")
}
name = "Rose"
}
}
protocol P {
func work(b: @escaping () -> ())
}
//正常
class C: P {
func work(b: @escaping () -> ()) {
}
}
如果我们没有使用@escaping,出错:
??操作符
var level: Int?
var startLevel = 1
var currentLevel = level ?? startLevel
func ??(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T?
func ??(optional: T?, defaultValue: @autoclosure () throws -> T) rethrows -> T
func ??(optinal: T?, defaultValue: @autoclosure () -> T) -> T {
switch optinal {
case .some(let value):
return value
case .none:
return defaultValue()
}
}
其实就是对可选值的应用。