Predict the output
What does this print?
func log(_ message: @autoclosure () -> String, enabled: Bool) {
if enabled { print(message()) }
}
func expensive() -> String {
print("computing")
return "msg"
}
log(expensive(), enabled: false)
log(expensive(), enabled: true)Hint 1 of 1
When does an autoclosure run?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B computing, msg
Correct. Only the second call evaluates the message.
Why not the others?
- A computing, computing, msg. With enabled false, the closure is never called, so
expensive()doesn't run. - C msg. Calling the closure runs
expensive(), which prints first. - D Nothing. The second call is enabled.