Closures
Overview
Closures are the single toughest thing to learn in Swift (HWS).
Closure is lean version of Function
Closure can be used in Function
Services like Siri and Network Connections use Closures in an app to make queries faster. (HWS)
How closures return a value
Here Closure returns nothing
let payment = { (user: String) in
print("Paying \(user)…")
}
Here Closure returns value
let payment = { (user: String) -> Bool in
print("Paying \(user)…")
return true
}
Functions vs. Closures
var invoice_amount = 20.0
// ----------------------------
func VAT_Incl_20_a (sum_wo_vat: Double) -> Double {
sum_wo_vat * 1.2
}
VAT_Incl_20_a(sum_wo_vat:invoice_amount)
// output: 24
print("VAT Incl \(VAT_Incl_20_a(sum_wo_vat: 20))")
// print: VAT Incl 24.0
print("---")
let VAT_Incl_20_b = {(sum_wo_vat: Double) in
print("VAT Incl \((sum_wo_vat)*1.2)")
}
VAT_Incl_20_b(invoice_amount)
// print: VAT Incl 24.0
Trailing Closure
If a function's final parameters are functions, use trailing closure syntax (HWS).
Shorthand Parameters
Use it in very specific conditions.
Sample Codes
let fixCar = { (problem: String) in
print("I fixed the \(problem).")
}
fixCar("ignition")
// print: I fixed the ignition.
Source: https://www.hackingwithswift.com/review/sixty/accepting-parameters-in-a-closure
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.
Source: https://www.hackingwithswift.com/review/sixty/accepting-parameters-in-a-closure
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
Source: https://www.hackingwithswift.com/review/sixty/accepting-parameters-in-a-closure
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.
*/
Source: https://www.hackingwithswift.com/review/sixty/accepting-parameters-in-a-closure
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.
*/
Source: https://www.hackingwithswift.com/review/sixty/accepting-parameters-in-a-closure
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
Source: https://www.hackingwithswift.com/review/sixty/accepting-parameters-in-a-closure
Sources
Videos
Articles / Documents
Last updated
Was this helpful?