How to achieve same behavior as with strongify in Swift?
Use a local variable to establish a strong reference to self
.
let c: () -> Void = {
[weak self] in
// assign unwrapped optional to another variable
guard let strongSelf: TypeOfSelf = self else {
return // or throw an exception, up to you
}
strongSelf.doSomething()
}
While the other answers work, another option is to use backticks. Doing so does away with having to define strongSelf
and allows using self
without having to unwrap optional self.
let c: () -> Void = {
[weak self] in
guard let `self` = self else {
throw NSError(domain: "self was destroyed", code: 1, userInfo: nil)
}
self.doSomethingNonOptionalSelf()
}