Why do I have to unwrap a weak self?

Spa*_*Dog 2 closures swift

I have created a class called VerifyObject, that contains a function with a signature like that

typealias handlerCodeID = (String) ->Void

class func checkPause(withID:String?,
  runOnPause: handlerCodeID?) 
Run Code Online (Sandbox Code Playgroud)

When I run that, I need to pass a weak self reference to inside the closure, using

VerifyObject.checkPause(withID: "abcde", 
  runOnPause: {[weak self] (objectID) in
    self.doSomething()
})
Run Code Online (Sandbox Code Playgroud)

Xcode complains that the self in doSomething must be unwrapped to

self!.doSomething()
Run Code Online (Sandbox Code Playgroud)

why? Does not make sense.

val*_*ale 7

self is inside a completion handler so it might not be there anymore once the callback gets fired (it might be a network operation or something that take some take and won't return a result for several seconds if not more).

You could check if self exists before accessing it instead of unwrapping:

VerifyObject.checkPause(withID: "abcde", 
  runOnPause: {[weak self] (objectID) in
    guard let self = self else { return }
    self.doSomething()
})
Run Code Online (Sandbox Code Playgroud)

Or even shorter only doSomething if self is not nil:

VerifyObject.checkPause(withID: "abcde", 
  runOnPause: {[weak self] (objectID) in
    self?.doSomething()
})
Run Code Online (Sandbox Code Playgroud)

Or if you're absolutely sure that self will exist:

VerifyObject.checkPause(withID: "abcde", 
  runOnPause: {(objectID) in
    self.doSomething()
})
Run Code Online (Sandbox Code Playgroud)

Just be mindful that this last one might cause reain cicles in case where the 2 objects have a strong reference to each other and they will never get deallocated.