Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`self` in Swift closure

Tags:

closures

swift

I want to understant self in Swift closure. For Ex -

() -> Void = { [weak self] in
    guard let `self` = self else { 
        self.callMethod2()
    }
    self.callMethod3()
}

Why we use backtick here? Is it good programming practice? How self is weakly captured here?

like image 633
srus2017 Avatar asked Dec 14 '22 16:12

srus2017


2 Answers

Swift 4.2 recently adopted a proposal to add this to the language:

guard let self = self else { return }

The proposed solution entails allowing self to be upgraded from a weak reference to a strong reference using optional binding.

For more details refer swift evolution proposal SE-0079

like image 87
Learner Avatar answered Jan 08 '23 12:01

Learner


self is a reserved word in Swift. Since you're creating a new local var called self you need to mark it with back-ticks, as explained in the link from rmaddy.

Note that the usual convention for mapping weak self to a strong var is to use the name strongSelf:

() -> Void = { [weak self] in
    guard let strongSelf = self else { 
        //your code to call self.callMethod2() can't succeed inside the guard (since in that case weak self is nil)
        //self.callMethod2()
        return   //You must have a statement like return, break, fatalEror, or continue that breaks the flow of control if the guard statement fails
    }
    strongSelf.callMethod3()
}
like image 34
Duncan C Avatar answered Jan 08 '23 12:01

Duncan C