You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reversedNames = names.sorted(by:{ s1, s2 in s1 > s2 })
Shorthand Argument Names
reversedNames = names.sorted(by:{ $0 > $1 })
Operator Methods
reversedNames = names.sorted(by:>)
Trailing Closures
func someFunctionThatTakesAClosure(closure:()->Void){
// function body goes here
}
// Here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure(closure:{
// closure's body goes here
})
// Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure(){
// trailing closure's body goes here
}
letstrings= numbers.map{(number)->Stringinvarnumber= number
varoutput=""repeat{
output =digitNames[number %10]! + output
number /=10}while number >0return output
}
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]
func someFunctionWithNonescapingClosure(closure:()->Void){closure()}classSomeClass{varx=10func doSomething(){someFunctionWithEscapingClosure{self.x =100}someFunctionWithNonescapingClosure{ x =200}}}letinstance=SomeClass()
instance.doSomething()print(instance.x)
// Prints "200"
completionHandlers.first?()print(instance.x)
// Prints "100"
Autoclosures
varcustomersInLine=["Chris","Alex","Ewa","Barry","Daniella"]print(customersInLine.count)
// Prints "5"
letcustomerProvider={ customersInLine.remove(at:0)}print(customersInLine.count)
// Prints "5"
print("Now serving \(customerProvider())!")
// Prints "Now serving Chris!"
print(customersInLine.count)
// Prints "4"
// customersInLine is ["Alex", "Ewa", "Barry", "Daniella"]
func serve(customer customerProvider:()->String){print("Now serving \(customerProvider())!")}serve(customer:{ customersInLine.remove(at:0)})
// Prints "Now serving Alex!"
// customersInLine is ["Ewa", "Barry", "Daniella"]
func serve(customer customerProvider:@autoclosure()->String){print("Now serving \(customerProvider())!")}serve(customer: customersInLine.remove(at:0))
// Prints "Now serving Ewa!"
// customersInLine is ["Barry", "Daniella"]
varcustomerProviders:[()->String]=[]func collectCustomerProviders(_ customerProvider:@autoclosure@escaping()->String){
customerProviders.append(customerProvider)}collectCustomerProviders(customersInLine.remove(at:0))collectCustomerProviders(customersInLine.remove(at:0))print("Collected \(customerProviders.count) closures.")
// Prints "Collected 2 closures."
forcustomerProviderin customerProviders {print("Now serving \(customerProvider())!")}
// Prints "Now serving Barry!"
// Prints "Now serving Daniella!"