Implicitly unwrapped optional (or IUO) may still contain nil
as a value! In case of IUO you will get a crash only when you call any method/variable on it (e.g. param.count
) OR when you assign it to a NON-Optional variable which will led to force unwrapping operation:
var param: String! = nil
var nonOptionalStr: String = param //<- Crash because it will try to force-unwrap param
Another example of a crash:
func foo(param: String!) -> String {
return param //<- Crash! As return type is non-optional String it will try to force unwrap the param.
}
On the other hand IUOs (as well as Optionals) are also of type Any
so if you pass a String!
containing nil to a method which expects Any
it will not crash because there will be no force-unwrapping operation as Any?
can be easily cast to Any
.
let str: String! = nil
print(str) //<- No Crash! Becaise print accepts Any, so there will be no force-unwrapping
//Output: nil
Another example with type Any
:
var a: Any? = nil
var b: Any = a //<- No Crash! As (Any?) is kind of (Any), though you will get a warning from compiler: Expression implicitly coerced from 'Any?' to 'Any'
print(b)
//Output: nil