importCocoa// ## Function Closure// The parameters have moved inside the braces, and the in keyword is there to mark the end of the parameter list and the start of the closure’s body itself// example 1, closure that takes no parameter, return booleanletdemo={()->Boolinprint("Paying an anonymous person…")returntrue}// example 2, closure that takes 2 params, return stringletpayment={(user:String,amount:Int)->Stringinifuser=="john"&&amount==10{return"yes"}return"no"}print(payment("john",8))// Notice: We don't use parameter names when calling a closure.// payment(user: "john", amount: 8) --> incorrect// :warning: Closures cannot use external parameter labels./*
var cutGrass = { (length currentLength: Double) in
// this is an invalid closure
}
*/// example 3, pass closure as function type parameterletteam=["Gloria","Suzanne","Piper","Tiffany","Tasha"]letcaptainFirstTeam=team.sorted(by:{(name1:String,name2:String)->Boolinifname1=="Suzanne"{returntrue}elseifname2=="Suzanne"{returnfalse}returnname1<name2})print(captainFirstTeam)// ## Trailing closure// 1, swift can infer parameter and return types in closure when pass as func parameter// 2, remove `(by:`, start the closure directlyletcaptainFirstTeam2=team.sorted{name1,name2inifname1=="Suzanne"{returntrue}elseifname2=="Suzanne"{returnfalse}returnname1<name2}// ## shorthand syntax with $0, $1, etc.letcaptainFirstTeam3=team.sorted{if$0=="Suzanne"{returntrue}elseif$1=="Suzanne"{returnfalse}return$0<$1}// ## Take function as parameterfuncmakeArray(size:Int,usinggenerator:()->Int)->[Int]{varnumbers=[Int]()for_in0..<size{letnewNumber=generator()numbers.append(newNumber)}returnnumbers}// ## Check point/*
Your input is this:
let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]
Your job is to:
Filter out any numbers that are even
Sort the array in ascending order
Map them to strings in the format “7 is a lucky number”
Print the resulting array, one item per line
*/letluckyNumbers=[7,4,38,21,16,15,12,33,31,49]letresult=luckyNumbers.filter({!$0.isMultiple(of:2)}).sorted().map({"\($0) is a luck number"})foreleinresult{print(ele)}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)