Force unwrapping after optional chaining

hi! i was having a discussion with a coworker recently, and we were trying to determine whether there are cases in which force unwrapping an optional value is guaranteed to be safe. the specific scenario in this instance was something like:

// self is a reference type
let callback: () -> Void = { [weak self] in
  // assume both `property1` and `doSomething(_:)` have no side effects on `self`
  self?.property1.doSomething(with: self!.property2)
}

one line of thinking was that the optional chain would either short circuit the force unwrap in the .None case, or, in the .Some case, would retain the unwrapped value for the entire evaluation of the expression, which would guarantee that the force unwrap would not be nil. i am skeptical that the initial optional unwrapping is guaranteed to extend the lifetime of the wrapped value for longer than is necessary to read the property1 value, but haven't been able to find conclusive evidence for either theory.

i was wondering if someone could help explain what exactly happens in expressions like this, or could point me to the relevant code in the compiler responsible for emitting the retain/release calls. thanks!

I think Joe’s answer here should help:

2 Likes

You might also find the responses in this thread interesting: The scope of an unwrapped optional in an optional chain

thanks for the quick responses! apologies that i didn't manage to find the existing threads that address this topic.