#23: Defer and Scope
Question
// Swift Quiz
— objc.io (@objcio) July 24, 2019
import Foundation
func foo(number: Int) {
if number % 2 == 0 {
defer {
print("1")
}
print("2")
} else {
print("3")
}
print("4")
}
foo(number: 4)
// What’s the output?
Solution
Solution: 214
— objc.io (@objcio) July 25, 2019
A `defer` is executed when its surrounding scope ends.
In the example above, its scope is the `true` branch of the if-statement, so it is executed directly after printing "2".https://t.co/s7500CWmAg