TIMEX TIMEX - 2 years ago 55
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.


I notice that I'm using
if self != nil
immediately, followed by
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 Source

Why don't you use if let?

if let weakSelf = self {

You could also use guard let:

guard let weakSelf = self else { return }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download