Before 4.2, self was the global reserved keyword, so if you marked self as weak in an escape closure, you would need to wrap it with ‘:
guard let `self` = self else { return }
Copy the code
While this solves the problem of variable names, it also creates another problem: a variable named self is not displayed in the console. So there’s also a common way to do this with individual names, like strongSelf:
doSomething(then: { [weak self] in
guard let strongSelf = self { else return }
strongSelf.doSomethingElse()
)
Copy the code
This does the trick, but it would be confusing for a new developer to see.
Of course, all I can do is give Apple dad constant advice. In 4.2, Apple finally answered the call! Self is no longer a reserved keyword in otional Binding. Now it’s fair to write:
guard let self = self else { return }
Copy the code
Of course, removing this restriction also means that self may not be self:
var number: Int? = nil
if let self = number {
print(self) // where self is number: Int
}
Copy the code
I hope you use self as the optional binding variable name in the right place so that you don’t get confused.
SE0079: Allow using optional binding to upgrade self from a weak to strong reference