I am looking for some of the difference/purpose of autoclosure and escaping closure in Swift. I know well that an escaping closure is something we want to execute after the function has been returned but I didn't get the concept of an autoclosure.
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
The autoclosure allows a function to wrap an expression in a closure so that it can be executed later or not at all.
A good example of the use of an autoclosure is the short-circuit behavior that happens with
||
.Consider this example:
Output:
The
||
operator uses short-circuit evaluation: The left-hand side (lhs) is evaluated first, and the right-hand side (rhs) is evaluated only if lhs evaluates to false.So, how is that implemented? Well,
||
is simply a function that takes two arguments that each evaluate to aBool
and||
combines them to return aBool
. But in the normal calling scheme of a function in Swift, the arguments are evaluated before the function is called. If||
was implemented in the obvious way:it would crash because of the execution of
willCrash()
before||
was called. So||
employs autoclosure to wrap the second statement in a closure so that it can delay evaluation until it is inside the||
function. If the first statement (which is evaluated before||
was called) istrue
then the result of the||
istrue
and the closure is not called thus avoiding the crash in this example.Here is the definition of
||
:Ignoring the throws/rethrows which is another topic, the implementation of
||
becomes:and
rhs()
is only called whenlhs == false
.The documentation is all thoroughly described (with examples), but if you have any other questions, please ask me