I'm new to Swift and I was reading the manual when I came across escaping closures. I didn't get the manual's description at all. Could someone please explain to me what escaping closures are in Swift in simple terms.
相关问题
- “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
Swift 4.1
Apple explains the attribute
escaping
clearly.I find this website very helpful on that matter Simple explanation would be:
Read more at the link I passed above! :)
I am going in a more simpler way.
Consider this example:
Consider the same example with an asynchoronous operation:
Escaping and non escaping closure were added for compiler optimization in Swift 3. You can search for the advantages of
nonescaping
closure.Consider this class:
someMethod
assigns the closure passed in, to a property in the class.Now here comes another class:
If I call
anotherMethod
, the closure{ self.number = 10 }
will be stored in the instance ofA
. Sinceself
is captured in the closure, the instance ofA
will also hold a strong reference to it.That's basically an example of an escaped closure!
You are probably wondering, "what? So where did the closure escaped from, and to?"
The closure escapes from the scope of the method, to the scope of the class. And it can be called later, even on another thread! This could cause problems if not handled properly.
To avoid accidentally escaping closures and causing retain cycles and other problems, use the
@noescape
attribute:Now if you try to write
self.closure = closure
, it doesn't compile!Update:
In Swift 3, all closure parameters cannot escape by default. You must add the
@escaping
attribute in order to make the closure be able to escape from the current scope. This adds a lot more safety to your code!