@escaping in Swift 5

Divesh Singh
2 min readSep 15, 2019

--

@escaping used with Closer only in swift.

Swift closures are @nonescaping closures by default.

When you pass any argument into a function in form of closure, you have to tell to complier whether your closure will get execute now (within function) or later (after function execution).

In case of now: The complier will not increase reference count of closer And it will execute with the function itself.

In case of later : The complier will increase reference count of closer as this closer will store in memory for later execution So that closer won’t accidentally be destroyed.

The thumb rule is : @escaping is used when closure will execute and produce result later.

For Example : API Call, Delay, Timer, or any response coming from server.

Complier will always give suggestion if @escaping required for your closure, so you don’t worried. Swift Complier is here to correct your code.

See the below example. Where I am using non escaping closure for the later executable closer and complier is ready to give suggestion.

@non-Escaping by Default so i am not writing

After accepting complier suggestion it becomes like this

Thanks

--

--

Divesh Singh
Divesh Singh

Written by Divesh Singh

Postgraduate from JEC Jabalpur || iOS and macOS developer, traveler |||| EM at Darwinbox | Ex-Samsung || Ex - Optimize IT Sys | Ex - R Systems

Responses (1)