2015年8月10日 星期一

【Swift 筆記 Draft】閉包 Closure


Syntax 語法:


{ (parameters) -> returnType in statements }
我們以下列為範例:

var students = ["John","David","Claire","Alvin"]

func sortAsc(s1:String, S2:String)->Bool {
   return s1 < s2
}

var sortedStudents = sorted(students,sortAsc)
閉包 closure 為 expression 表達式,可作為函式之參數使用。例如: var sortedStudents = sorted(students, {(s1:String, S2:String)->Bool in return s1 < s2} ) 閉包簡化 1: 省略參數資料型態 students 此 Array 的元素資料型態為 String,而閉包參數的資料型態亦為 String,此時可省略後者資料型態之宣告。例如:

var sortedStudents = sorted(students, {(s1, s2) -> Bool in return s1 < s2} )
閉包簡化 2: 省略返回值 函式 sorted 為 Swift 內建函式[參考:1],其以函式為參數,而這函式參數的回傳值為 Bool,所以可省略此閉包的回傳值。例如:

var sortedStudents = sorted(students, {(s1, s2) in return s1 < s2} )
閉包簡化 3: 省略 return 保留字 已知閉包的回傳資料型態為 Bool,且無其他程式 statements,可省略此 return 保留字。例如:

var sortedStudents = sorted(students, {(s1, s2) in s1 < s2} )
閉包簡化 4: 省略閉包重複參數 S1 與 S2 參數 S1 與 S2 在閉包中重複,可再簡化,但 Swift 不允許簡化為 {(, ) in s1 < s2} ) 或 {(s1, s2) in < } )。前者無法將 S1 與 S2 這兩個參數帶入,而後者雖能帶入此參數,但 Swift 無法判斷是 S1 < S2 或 S2 < S1。因此 Swift 採用腳本 Script 命令中帶入參數的方式,使用 $0, $1, ... 等表示參數1 ,參數 2 等。例如:

var sortedStudents = sorted(students, {$0 < $1} )
閉包簡化 5: 閉包參數再簡化 閉包 {$0 < $1} 表達式說明為 2 個參數的比較,在此僅以 < 此符號即可表達,所以我們可再省略 $0 與 $1 這兩個參數。例如:

var sortedStudents = sorted(students, < )
尾隨閉包 Tailing Closure 尾隨閉包顧名思義為函式最後一個參數被宣告為閉包。若此函式只有此唯一閉包參數,可將閉包寫在函式外面。例如:

var sortedStudents = sorted(students){$0 < $1}
若函式只有一個參數要帶入到閉包,我們可改寫如下:

var sortedStudents = sorted{$0 < $1}
Reference 1. Swift Standard Library Reference, https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/Array.html sorted(_:) Returns an array containing elements from the array sorted using a given closure. Declaration func sorted(isOrderedBefore: (T, T) -> Bool) -> [T] Discussion Use this method to return a new array containing sorted elements from the array. The closure that you supply for isOrderedBefore should return a Boolean value to indicate whether one element should be before (true) or after (false) another element: let array = [3, 2, 5, 1, 4] let sortedArray = array.sorted { $0 < $1 } // sortedArray is [1, 2, 3, 4, 5] let descendingArray = array.sorted { $1 < $0 } // descendingArray is [5, 4, 3, 2, 1] 2. http://chain.logdown.com/tags/swift

沒有留言:

張貼留言

prettyPrint();