swift - 閉包

內(nèi)嵌函數(shù)

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
})
// 因排序閉包為實際參數(shù)來傳遞給函數(shù),故 Swift 能推斷它的形式參數(shù)類型和返回類型
// 因為所有的類型都能被推斷,返回箭頭 ( ->) 和圍繞在形式參數(shù)名周圍的括號也能被省略
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
// 從單表達式閉包隱式返回,單表達式閉包能夠通過從它們的聲明中刪掉 return 關(guān)鍵字來隱式返回它們單個表達式的結(jié)果
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
// 簡寫的實際參數(shù)名
reversedNames = names.sorted(by: { $0 > $1 } )
// 運算符函數(shù)
reversedNames = names.sorted(by: >)

尾隨閉包

//如果你需要將一個很長的閉包表達式作為函數(shù)最后一個實際參數(shù)傳遞給函數(shù),使用尾隨閉包將增強函數(shù)的可讀性
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 }
//如果閉包表達式作為函數(shù)的唯一實際參數(shù)傳入,而你又使用了尾隨閉包的語法,那你就不需要在函數(shù)名后邊寫圓括號了:
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"]

捕獲值

//內(nèi)嵌函數(shù)
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incremented
}
//調(diào)用
 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
/**
* 再次調(diào)用原來增量器 ( incrementByTen )  繼續(xù)增加它自己的變量 runningTotal 的值,并且不會影響 incrementBySeven 捕獲的變量 runningTotal 值
*/
   incremByTen()
  //returns a value of 40

閉包是引用類型

//無論你什么時候安賦值一個函數(shù)或者閉包給常量或者變量,你實際上都是將常量和變量設(shè)置為對函數(shù)和閉包的引用。這上面這個例子中,閉包選擇 incrementByTen 指向一個常量,而不是閉包它自身的內(nèi)容。
這也意味著你賦值一個閉包到兩個不同的常量或變量中,這兩個常量或變量都將指向相同的閉包:
let alsoIncrementByTen = incrementByTen
  alsoIncrementByTen()
  //return a value of 50

逃逸閉包 (@escaping )

//當閉包作為一個實際參數(shù)傳遞給一個函數(shù)的時候,我們就說這個閉包逃逸了,因為它可以在函數(shù)返回之后被調(diào)用。當你聲明一個接受閉包作為形式參數(shù)的函數(shù)時,你可以在形式參數(shù)前寫 @escaping 來明確閉包是允許逃逸的。

var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}
func someFunctionWithNonescapingClosure(closure: () -> Void) {
    closure()
}
 // 逃逸閉包:閉包可以逃逸的一種方法是被儲存在定義于函數(shù)外的變量里
//  非逃逸:僅調(diào)用一次
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"

對比一下使用自動閉包的區(qū)別

//傳一個閉包作為實際參數(shù)到函數(shù)的時候,你會得到與延遲處理相同的行為。
// 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!"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift 中的閉包是自包含的函數(shù)代碼塊,可以在代碼中被傳遞和使用。類似于OC中的Block以及其他函數(shù)的匿名函數(shù)...
    喬克_叔叔閱讀 556評論 1 3
  • 閉包是自包含的函數(shù)代碼塊,可以在代碼中被傳遞和使用。Swift 中的閉包與 C 和 Objective-C 中的代...
    窮人家的孩紙閱讀 1,811評論 1 5
  • 閉包可以從定義它們的上下文中捕獲和存儲對任何常量和變量的引用。 這被稱為關(guān)閉這些常量和變量。 Swift處理所有的...
    Joker_King閱讀 638評論 0 2
  • * 閉包 是自包含的函數(shù)代碼塊,可以在代碼中被傳遞和使用。swift中的閉包和Objective-C中的代碼塊(b...
    EndEvent閱讀 894評論 4 8
  • 1.閉包的概念:閉包(Closures)是自包括的功能代碼塊,能夠在代碼中使用或者用來作為參數(shù)傳值。在Swift中...
    GY1994閱讀 247評論 0 2

友情鏈接更多精彩內(nèi)容