swift語言點評四-Closure

總結:整個Closure的做用在於簡化語言表述形式。git

 

1、閉包的簡化express

 

Closure expression syntax has the following general form:api

 

  • { () -> in
  •     }

 

  • reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
  •     return s1 > s2
  • })

 

Because the sorting closure is passed as an argument to a method, Swift can infer the types of its parameters and the type of the value it returns. 閉包

reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )異步

 

Implicit Returns from Single-Expression Closureside

reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )函數

 

Shorthand Argument Namesthis

Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.orm

 

reversedNames = names.sorted(by: { $0 > $1 } )ci

 

Operator Methods

reversedNames = names.sorted(by: >)

 

 

2、拖尾變換

  • func someFunctionThatTakesAClosure(closure: () -> Void) {
  •     // function body goes here
  • }
  •  
  • // Here's how you call this function without using a trailing closure:
  •  
  • someFunctionThatTakesAClosure(closure: {
  •     // closure's body goes here
  • })
  •  
  • // Here's how you call this function with a trailing closure instead:
  •  
  • someFunctionThatTakesAClosure() {
  •     // trailing closure's body goes here
  • }

 

閉包的實如今函數參數列表外;

 

再次精簡

 

reversedNames = names.sorted() { $0 > $1 }

reversedNames = names.sorted { $0 > $1 }

 

 

 

徹底移出

  • 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
  • }

 

Closures Are Reference Types

Whenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function or closure.

 

Escaping Closures

異步解決方案

 

Autoclosures

表達式語句

  • // 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!"
相關文章
相關標籤/搜索