Explicitly unwrapping optional nil does not cause crash

As of Swift 3, “Implicitly unwrapped optional” is not a separate type, but an attribute on the declaration of a regular/strong optional. For the details, see SE-0054 Abolish ImplicitlyUnwrappedOptional type.

A function with an IUO return type can return nil, and assigning the return value to a variable makes that a regular optional:

func foo() -> Int! {
    return nil
}

let x = foo() // Type of `x` is `Int?`
print(x) // nil

Only if evaluation as an optional is not possible then the value will be forced-unwrapped (and cause a runtime exception is the value is nil):

let y = 1 + foo() // Fatal error: Unexpectedly found nil while unwrapping an Optional value

In your case, your

override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath!

method overrides the UITableViewController method

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?

and can return nil. This does not crash unless the caller unwraps the value.


Remark: The above is meant as an explanation why your code compiles and works. Generally, I do not see a good reason to use implicitly unwrapped optional return types. The main use-cases of IUOs are stated in SE-0054:

The ImplicitlyUnwrappedOptional ("IUO") type is a valuable tool for importing Objective-C APIs where the nullability of a parameter or return type is unspecified. It also represents a convenient mechanism for working through definite initialization problems in initializers.

Tags:

Swift