Actually, closures are functions.
function as a condition
Closed-Packet expression
First declare an array
var names = ["Charis""Alex""Ewa""Barry""Daniella"]
Sort this array alphabetically
Declaring a closed-packet function
func backwards(s1: String, s2:String) -> Bool { return s1 > s2}
The sorted () function returns an array, and the sort () function returns NULL, sorting itself
///传入闭包函数names.sort(backwards)
Using a closure expression
//闭包表达式就是一个函数在花括号里面names.StringString-> inreturn> s2})
And because the value of Swift is an inferred type
The above can also be simplified
varinreturn s1 > s2})
Single-closed Baoyin return
//会隐式returnin s1 > s2})
Name abbreviation
names.sort({$0$1})
operator functions
names.sort(>)
Trailing closures
Sometimes closure expressions are too cumbersome to write closures in curly braces that follow the calling function.
//调用sort函数,后面添加花括号,然后闭包表达式就写在这里names.sort() {$0$1}
Official examples
//Declare a dictionary LetDigitnames = [0:"Zero",1:"One",2:"both",3:"three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine"]//An array Letnumbers = [ -, -,510]//Call the map function with the incoming closure inside Letstrings = numbers.map{//Pass in a number to return a string(varNumber)String inch varOutput ="" whileNumber >0{output = digitnames[number%Ten]! + Output//find each number and convert to a stringNumber/=Ten}returnOutput
Value capture
first the closure is the reference type
Official examples
///defines a function that returns () type Int () Func makeincrementor (forincrement amount:int) -> () - > Int {var runningtotal = 0 //a closure function func incrementor () -> Int {runningtotal += amount; return runningtotal} //return this closure, At this point the closure already contains the value of RunningTotal and amount return incrementor}
let10)let1)incrementByTen1() //10 所以值会被闭包一直保留incrementByTen1() //20incrementByTen2() //1
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Swift-Summary" closure