#29: Interesting Uses of @autoclosure
@autoclosure wraps an expression in a closure automatically. It is useful when you want a convenient API but you still want the argument to be evaluated lazily.
A classic example is logging only when needed:
func debugLog(_ message: @autoclosure () -> String) {
#if DEBUG
print(message())
#endif
}
debugLog(expensiveDebugDescription())
If DEBUG is off, the expensive expression is never evaluated.
Use @autoclosure sparingly. It can make APIs pleasant, but it also hides the fact that a closure is involved, so it is best reserved for small helper functions where the behavior is obvious.