TIMEX TIMEX - 7 months ago 5
Swift Question

I find myself using "if self != nil" a lot because of [weak self] ...is this normal?

Example (in my view controller):

RESTApi.fetchUser() { [weak self] Void in
if self != nil { //the view controller is still here.
self!.items.append(stuff)
self!.whatever

}
}


I notice that I'm using
if self != nil
immediately, followed by
self!
everywhere. Is there a better way? I feel like this is against the Swift way.

Note: I use [weak self] because my ViewController could be nil (if the user goes back before the REST Api downloads the data).

Answer

Why don't you use if let?

if let weakSelf = self {
    weakSelf.items.append(stuff)
    ...
}

You could also use guard let:

guard let weakSelf = self else { return }

weakSelf.items.append(stuff)
...
Comments