How to cast optional T? to T

That's not really how this works.

Optionals weren't some inconvenience the Swift language designers threw your way that you should just try to rid yourself of in by any means.

They're intentionally made to make you pause and consider: "how should I handle nil here?" in a deliberate, compiler-checked way.

As @Jumhyn is hint at, there's basically three options:

  1. Only do something if it's not nil (if let, guard let, etc)
  2. Substitute a default value instead of nil (??)
  3. Assert that nil is impossible (for reasons that you otherwise can't express to the type system), using a force unwrap (!)
3 Likes