What about this doesn't work? Since t here is nil, of course the program will crash (since t is, at runtime, not a T), but the following compiles and runs fine for me:
var t: Int? = nil
let some = t as! Int
we do get a warning that as! is inappropriate here, because this operation is idiomatically spelled with the force-unwrap operator:
var t: Int? = nil
let some = t!
Again, the code as written will crash, but if t does have a value, this will work to turn a T? into a T:
var t: Int? = 0
let some = t! // some has type 'Int', value '0'
Yeah, that's the warning I mentioned in my previous post.
Functionally, they're no different, and it's just a warning so you can compile and run the as! version just fine. But because there's another shorter and more idiomatic way to spell the force-unwrap operation, the compiler takes that as a signal that you might have meant to do something else and presents a warning.
The nil-coalescing operator ( a ?? b ) unwraps an optional a if it contains a value, or returns a default value b if a is nil . The expression a is always of an optional type. The expression b must match the type that’s stored inside a .
The nil-coalescing operator is shorthand for the code below: