#94: @autoclosure in Swift APIs

@autoclosure wraps an expression in a closure automatically, which is useful when you want lazy evaluation but a simple call site.

func debugOnly(_ message: @autoclosure () -> String) {
    #if DEBUG
    print(message())
    #endif
}

debugOnly(expensiveDescription())

If DEBUG is off, the expensive expression never runs.

This is a good fit for assert-like helpers and logging APIs, but it should be used sparingly since it hides the closure from the caller.


I'm also on Twitter and GitHub.

Subscribe via RSS.