Swift — @autoclosure attribute

public func precondition(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
file: StaticString = #file,
line: UInt = #line
)
precondition(3 > 2, "Where do you think you're going?")
extension Int {
mutating func increase(_ operation: @autoclosure () -> Int) {
precondition(
(self + operation()) > self,
"Decreasing a value is not allowed"
)
self += operation() }
}
var number = 0number.increase(2*3) // prints 6
number.increase(3+2) // prints 11
number.increase(1–8) // Error: Decreasing a value is not allowed
extension Array {
func applied<T>(_ operation: @autoclosure () -> [T]) -> [T] {
return operation()
}
}
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]let evens = numbers.applied(numbers.filter { $0.isMultiple(of: 2) })
let doubles = numbers.applied(numbers.map { $0 * 2 })
let strings = numbers.applied(numbers.map(String.init))
extension Array {
@discardableResult
func removed(_ operation: @autoclosure () -> (Self.Element)) -> Self.Element {
return operation()
}
}
let n1 = numbers.removed(numbers.remove(at: 2)) // prints 3
let n2 = numbers.removed(numbers.removeFirst()) // prints 1
let n3 = numbers.removed(numbers.removeLast()) // prints 10
func isValid(_ lhs: Bool, _ rhs: @autoclosure () -> Bool) -> Bool {
guard lhs else {
return false
}
return rhs()
}
if isValid(numbers.count > 0, numbers.last == 10) {
// perform some work
}

Conclusion

The @autoclosure attribute is a convenient way to improve code legibility by passing a closure as an argument.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store