let fixCar = { (problem: String) in
print("I fixed the \(problem).")
}
fixCar("ignition")
// print: I fixed the ignition.
With Integer
let makeReservation = { (people: Int) in
print("I'd like a table for \(people), please.")
}
makeReservation(2)
// print: I'd like a table for 2, please.
With Case Conditional
var cutGrass = { (currentLength: Int) in
switch currentLength {
case 0...1:
print("That's too short")
case 2...3:
print("It's already the right length")
default:
print("That's perfect.")
}
}
cutGrass(2)
// print: It's already the right length
With for
let rowBoat = { (distance: Int) in
for _ in 1...distance {
print("I'm rowing 1km.")
}
}
rowBoat(3)
/*
print:
I'm rowing 1km.
I'm rowing 1km.
I'm rowing 1km.
*/
Returning with if-else conditional
var flyDrone = { (hasPermit: Bool) -> Bool in
if hasPermit {
print("Let's find somewhere safe!")
return true
}
print("That's against the law.")
return false
}
flyDrone(true)
flyDrone(false)
/*
print:
Let's find somewhere safe!
That's against the law.
*/
Returning with switch-case conditional
let measureSize = { (inches: Int) -> String in
switch inches {
case 0...26:
return "XS"
case 27...30:
return "S"
case 31...34:
return "M"
case 35...38:
return "L"
default:
return "XL"
}
}
measureSize(36) // return: L
print(measureSize(36)) // print: L
Sources
Videos
Articles / Documents
If a function's final parameters are functions, use trailing closure syntax ().