//Playground-noun:a Place where people can playImport UIKit//The closure in Swift is similar to the blocks in C and OC//1. Use context to infer parameters and return value Types 2. A single expression closure can omit the return keyword 3. The parameter name is abbreviated 4. Trailing closed packet Syntax//The closure expression in indicates that the parameter and the return value have been expressed, followed by the package body/** {(parmeters), return type in statements}*/var names= ["Anna","Alex","Ewa","Barry","Daniella"]sorted (names, {(s1:string, s2:string)-Boolinch returnS1 > S2//single expression closure can omit the return keyword here return can be omitted})//infer type from context//when a closure is used as a parameter method parameter, because the parameter in the method already has a type (string, string), Bool, Swift can infer the closure parameter and return value from the context, so the parameters and the return value of the closure can be omittedSorted (names, {s1, s2inch returnS1 >S2})//parameter 0, which is inferred by using the $ + numeric reference, indicates that the firstSorted (names, {return$0> $1})//official documents Here say return can be omitted, but Xcode has always reported an ambiguous solution {$ As String > $ as String}//in Swift, for the string > method, a parameter of 2 string is received, and a bool value is returned, which coincides with the closure and can be passed directly into theSorted (names, >)//Trailing cloures Use scenario: If you use a closure as the last parameter of a method and the closure is very longFunc Somefunctiontakescloures (cloures: ()()) {println ("Do some thing")}//do not use trailing cloures callSomefunctiontakescloures ({//implement closures here})//using trailing clouressomefunctiontakescloures () {//implement closures here}//If the closure is the only parameter of the method and you use trailing cloures, you can omit () when calling the methodSomefunctiontakescloures {//implement closures here}//calling the sorted method using trailing ClouresSorted (names) {return$0> $1}//Capturing ValuesFunc makeincrementor (forincrement amount:int),Int {var runningtotal=0func incrementor ()-Int {runningtotal+=AmountreturnRunningTotal}returnIncrementor}//the Incrementor method has no arguments, but it can capture variables from the context using the
swift-7-Closure Package