Given the following in Swift:
var optionalString: String?
let dict = NSDictionary()
What is the practical difference between the following
I am novice to Swift and writing this example trying to explain as i understand about 'optionals'. If i am wrong please correct me.
Thanks.
class Optional {
var lName:AnyObject! = "1"
var lastName:String!
}
let obj = Optional()
print(obj.lName)
print(obj.lName!)
obj.lastName = obj.lName as? String
print(obj.lastName)
(1) : obj.lastName = obj.lName as! String
vs
(2) : obj.lastName = obj.lName as? String
Ans : (1) Here programmer is damm sure that “obj.lName” contains string type object. So just give that value to “obj.lastName”.
Now, if programmer is correct means "obj.lName" is string type object, then no problem. "obj.lastName" will set to the same value.
But if programmer is wrong means "obj.lName" is not string type object i.e. it contains some other type object like "NSNumber" etc. Then CRASH (Run Time Error).
(2) Programmer is not sure that “obj.lName” contains string type object or any other type object. So set that value to “obj.lastName” if it is string type.
Now, if programmer is correct means “obj.lName” is string type object, then no problem. “obj.lastName” will set to the same value.
But if programmer is wrong means obj.lName is not string type object i.e. it contains some other type object like "NSNumber" etc. Then “obj.lastName” will set to the nil value. So, No Crash (Happy:)