user1107173 user1107173 - 5 months ago 17
Swift Question

Swift: Force Unwrapped returns nil without crashing

Below is the code I have in playground:

let aNumber : NSNumber? = nil

func testFuction() -> NSNumber!{
return aNumber
}

dump(testFuction())


Output:

- nil


I am confused as to why it's not crashing. The return value
NSNumber!
is obviously nil, but it's being force unwrapped. Shouldn't this be crashing? Please explain.

Answer

You are returning an implicitly unwrapped optional, NSNumber!. The underlying data type returned is an optional, but it will automatically be unwrapped every time you use it. Swift includes this type so that you don't have to use exclamation points after variables that you know will be non-nil after a certain point (for instance, an instance variable that starts off as nil but is initialized before it is ever used). Implicitly unwrapped optionals are allowed to contain nil values, but you will trigger a runtime error if the variable is nil when you actually try to use it because it is force-unwrapped at the point of use.