swift - 闭包

内嵌函数

let names = ["Chris","Alex","Ewa","Barry","Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
    return s1 > s2
}
var reversedNames = names.sorted(by: backward)
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]

闭包表达式语法

{ (parameters) -> (return type) in
    statements
  }
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1 > s2
})
// 因排序闭包为实际参数来传递给函数,故 Swift 能推断它的形式参数类型和返回类型
// 因为所有的类型都能被推断,返回箭头 ( ->) 和围绕在形式参数名周围的括号也能被省略
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
// 从单表达式闭包隐式返回,单表达式闭包能够通过从它们的声明中删掉 return 关键字来隐式返回它们单个表达式的结果
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
// 简写的实际参数名
reversedNames = names.sorted(by: { $0 > $1 } )
// 运算符函数
reversedNames = names.sorted(by: >)

尾随闭包

//如果你需要将一个很长的闭包表达式作为函数最后一个实际参数传递给函数,使用尾随闭包将增强函数的可读性
func someFunctionThatTakesAClosure(closure:() -> Void){
       //function body goes here
  }
 
  //here's how you call this function without using a trailing closure
 
  someFunctionThatTakesAClosure({
       //closure's body goes here
  })
    
  //here's how you call this function with a trailing closure instead
      
  someFunctionThatTakesAClosure() {
       // trailing closure's body goes here
  }
//eg:
reversedNames = names.sorted() { $0 > $1 }
//如果闭包表达式作为函数的唯一实际参数传入,而你又使用了尾随闭包的语法,那你就不需要在函数名后边写圆括号了:
reversedNames = names.sorted { $0 > $1 }
// 当闭包很长以至于不能被写成一行时尾随闭包就显得非常有用了
// eg:
let digitNames = [
     0: "Zero",1: "One",2: "Two",  3: "Three",4: "Four",
     5: "Five",6: "Six",7: "Seven",8: "Eight",9: "Nine"
  ]
  let numbers = [16,58,510]
let strings = numbers.map {
    (number) -> String in
    var number = number
    var output = ""
    repeat {
        output = digitNames[number % 10]! + output
        number /= 10
    } while number > 0
    return output
}
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]

捕获值

//内嵌函数
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incremented
}
//调用
 let incrementByTen = makeIncrementer(forIncrement: 10)
 incrementByTen()
  //return a value of 10
  incrementByTen()
  //return a value of 20
  incrementByTen()
  //return a value of 30

/**如果你建立了第二个 incrementer ,它将会有一个新的、独立的 runningTotal 变量的引用*/
let incrementBySeven = makeIncrementer(forIncrement: 7)
incrementBySeven()
// returns a value of 7
/**
* 再次调用原来增量器 ( incrementByTen )  继续增加它自己的变量 runningTotal 的值,并且不会影响 incrementBySeven 捕获的变量 runningTotal 值
*/
   incremByTen()
  //returns a value of 40

闭包是引用类型

//无论你什么时候安赋值一个函数或者闭包给常量或者变量,你实际上都是将常量和变量设置为对函数和闭包的引用。这上面这个例子中,闭包选择 incrementByTen 指向一个常量,而不是闭包它自身的内容。
这也意味着你赋值一个闭包到两个不同的常量或变量中,这两个常量或变量都将指向相同的闭包:
let alsoIncrementByTen = incrementByTen
  alsoIncrementByTen()
  //return a value of 50

逃逸闭包 (@escaping )

//当闭包作为一个实际参数传递给一个函数的时候,我们就说这个闭包逃逸了,因为它可以在函数返回之后被调用。当你声明一个接受闭包作为形式参数的函数时,你可以在形式参数前写 @escaping 来明确闭包是允许逃逸的。

var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}
func someFunctionWithNonescapingClosure(closure: () -> Void) {
    closure()
}
 // 逃逸闭包:闭包可以逃逸的一种方法是被储存在定义于函数外的变量里
//  非逃逸:仅调用一次
class SomeClass {
    var x = 10
    func doSomething() {
        someFunctionWithEscapingClosure { self.x = 100 }
        someFunctionWithNonescapingClosure { x = 200 }
    }
}
let instance = SomeClass()
instance.doSomething()
print(instance.x)
// Prints "200"
 
completionHandlers.first?()
print(instance.x)
// Prints "100"

自动闭包(匿名block?)

var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
// prints "5"
 
let customerProvider = { customersInLine.removeAtIndex(0) }
print(customersInLine.count)
// prints "5"
 
print("Now serving \(customerProvider())!")
// prints "Now serving Chris!"
print(customersInLine.count)
// prints "4"

对比一下使用自动闭包的区别

//传一个闭包作为实际参数到函数的时候,你会得到与延迟处理相同的行为。
// customersInLine is ["Alex", "Ewa", "Barry", "Daniella"]
func serve(customer customerProvider: () -> String) {
    print("Now serving \(customerProvider())!")
}
serve(customer: { customersInLine.remove(at: 0) } )
// Prints "Now serving Alex!"

// customersInLine is ["Ewa", "Barry", "Daniella"]
func serve(customer customerProvider: @autoclosure () -> String) {
    print("Now serving \(customerProvider())!")
}
serve(customer: customersInLine.remove(at: 0))
// Prints "Now serving Ewa!"
// 如果你想要自动闭包允许逃逸,就同时使用 @autoclosure 和 @escaping 标志。
// customersInLine is ["Barry", "Daniella"]
var customerProviders: [() -> String] = []
func collectCustomerProviders(_ customerProvider: @autoclosure @escaping () -> String) {
    customerProviders.append(customerProvider)
}
collectCustomerProviders(customersInLine.remove(at: 0))
collectCustomerProviders(customersInLine.remove(at: 0))
 
print("Collected \(customerProviders.count) closures.")
// Prints "Collected 2 closures."
for customerProvider in customerProviders {
    print("Now serving \(customerProvider())!")
}
// Prints "Now serving Barry!"
// Prints "Now serving Daniella!"

你可能感兴趣的:(swift - 闭包)