Swift’s @autoclosure is a syntax sugar attribute applied to a function argument to implicitly create a closure out of a passed in argument. @autoclosure can be useful in situations where you have a sequence of conditions and you want to keep the execution of these expressions in order, and clean in terms of readability without explicitly defining the closures.
func doSomething(_ doSomething: () -> Void, on condition: @autoclosure () -> Bool) {
guard conditions() else {
return
}
doSomething()
}
/*
The function doSomething(_:on) can be called in multiple ways.
*/
// 1. Using curly braces.
doSomething({
// logic to be executed...
}, on: {
return !self.subviews.isEmpty && self.subviews.allSatisfy { $0.isHidden }
})
// 2. Without using curly braces.
doSomething({ // logic to be executed... }, on: !subviews.isEmpty)
// 3. Passing another function as a parameter for more complicated condition
doSomething({ // logic to be executed... }, on: anotherFunction())
Although @autoclosure can be very tempting in multiple situations, but overusing it can make your code hard to understand. The context and function name should make it clear that evaluation is being deferred.
Thanks for reading! ?