? ? Swift standard library provide a method called sort ( _: ) ,which sort an array of a known type,base on? the output of a sorting closure that you provide.Once it completes the sorting process,the sort ( _: )? method returns a new array of the same size and type as old one,with its elements in the correct sorted order.the original array isn't modified by the sort ( _: ) method.
? ?The closure expression example below use sort ( _: ) to sort a array of string type in reverse alphabetical order.Here is the initial array to be sorted:
let names = ["Chris","Alex","Ewa","Barry","Daniella"]
swift 標(biāo)準(zhǔn)庫(kù)提供 ?sort ( _: ) 排序方法,它可以給一個(gè) 已知類型 的array排序牺荠。排序規(guī)則基于你寫的 排序 閉包翁巍。當(dāng)排序完成時(shí),sort ( _: ) 方法返回一個(gè)新數(shù)組休雌,新數(shù)組與原來(lái)的數(shù)組有相同的大小和類型灶壶。但數(shù)組中元素排序變了。原數(shù)組不會(huì)被sort ( _: ) 方法修改杈曲。
下面的閉包表達(dá)式使用sort ( _: )方法給 一個(gè)string類型的 數(shù)組 按 字母逆序 排序驰凛。
let names = ["Chris","Alex","Ewa","Barry","Daniella"]
翻譯就先到這,來(lái)總結(jié)一下閉包担扑。舉個(gè)栗子
{ ( parameters ) -> Return Type in
? ? Statements
}
大括號(hào)(curly brace:卷曲的括號(hào))里面是閉包內(nèi)容恰响, 小括號(hào)()里面是參數(shù)argument ,->?
后面寫返回值的類型涌献,在 in 后面開始寫 閉包體語(yǔ)句胚宦。in 來(lái)提示 閉包中參數(shù)和返回值的定義都已完成。