“An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.”
var customersInLine = ["james","kim","lee","richard","micheal","blondes","linda"]
let customerProvider = { customersInLine.remove(at:0) } // autoclosure : ()->String
print( customersInLine.count )
print( customerProvider() )
print( customersInLine.count )
//not autoclosure
func serve(customer: ()->String){
print("serve:\(customer())")
}
serve(customer: { customersInLine.remove(at:0) } )
print (customersInLine.count)
//autoclosure
func serveAutoclosure(customer: @autoclosure ()->String ){
print("serve by Autoclosure:\(customer())")
}
serveAutoclosure(customer: customersInLine.remove(at:0))
print (customersInLine.count)
// + escaping
var tempClosures : [()->String] = []
func collectClosures(itemClosure: @autoclosure @escaping ()->String){
tempClosures.append(itemClosure)
}
collectClosures(itemClosure: customersInLine.remove(at:0))
collectClosures(itemClosure: customersInLine.remove(at:0))
for i in tempClosures {
print("customer:\(i()), count:\(customersInLine.count)")
}
댓글 없음:
댓글 쓰기