Nil-Coalescing Operator – Day 39
When is it ok to force unwrap a variable? Only if the variable is not equal to nil. Otherwise you will crash the program. Make some code that unwraps a value safely.
var str:String? = "hi"
var str2 = "Dodged a crashing bullet"
let res = str != nil ? str! : str2
print("res --- \(res)")
/**In the above code try changing str to nil
var str:String? = nil"
What do you notice? It will print str2 value because str is nil
#1 str != nil"
This checks that str is not nil if is is not nil then it is ok to use str Which is the first option on the left…which is true If false then the
str! : str2"
value on the right is used.