Swift 4.2
Since Swift 4.2 you can use the following syntax:
{ [weak self] in
guard let self = self else { return }
// self is not an optional anymore, it is held strongly
}
For more see the Swift evolution proposal SE-0079.
Sometimes other approaches than using guard let might be useful as well (e.g. shorter or more readable). See also the following section, just replace strongSelf with self in few examples.
Swift 4.1 and earlier
Because guard let `self` = self is a compiler bug as stated by Chris Lattner I would try to avoid it. In your example you can use just simple optional chaining:
return { [weak self] in
self?.doSomethingNonOptionalSelf()
}
Sometimes you might need to use self as a parameter. In such case you can use flatMap (on an optional type):
{ [weak self] in
self.flatMap { $0.delegate?.tableView($0, didSelectRowAt: indexPath) }
}
In case you need to do something more complicated you can use if let construct:
{ [weak self] in
if let strongSelf = self {
// Do something more complicated using strongSelf
}
}
or guard let construct:
{ [weak self] in
guard let strongSelf = self else { return }
// Do something more complicated using strongSelf
}
or you can create a private method:
{ [weak self] in
self?.doSomethingMoreComplicated()
}
...
private func doSomethingMoreComplicated() {
// Do something more complicated
}