There are many useful attribute keywords in Swift. @Autoclosure is one of them and is a very common attribute.

To better illustrate what this property does, we’ll use an ifelse example.

func ifelse<V> (_ condition: Bool.valueTrue: () - >V.valueFalse: () - >V) -> V {
    condition ? valueTrue() : valueFalse()
}
Copy the code

The ifelse implementation is very simple: when condition is true, valueTrue is executed and the value is returned. If false, the valueFalse function is executed.

We call this function:

/ / swift, 5.4
let value = ifelse(.random()) {
    100
} valueFalse: {
    0
}
Copy the code

Only a simple function is called, but the arguments must be wrapped in a closure. Is there a way to fix it?

/ / swift, 5.4
func ifelse2<V> (_ condition: Bool.valueTrue: @autoclosure() - >V.valueFalse: @autoclosure() - >V) -> V {
    condition ? valueTrue() : valueFalse()
}
Copy the code

In ifelse2, valueTrue and valueFalse add the @autoclosure attribute keyword. But the calling code is much cleaner:

let value2 = ifelse2(.random(), valueTrue: 100, valueFalse: 0)
Copy the code

@autoclosure will automatically convert syntax like 100 toclosure execution.

role

@autoclosure does this:

  • 1. Use@autoclosureKeywords simplify closure invocation
  • 2. Use@autoclosureKeyword can delay closure execution

For point 2, it’s not @Autoclosure itself, it’s the closure itself. Both valueTrue and valueFalse in the code are executed when called.