Downcasting optionals in Swift: as? Type, or as! Type?

前端 未结 9 1693
耶瑟儿~
耶瑟儿~ 2020-11-29 17:32

Given the following in Swift:

var optionalString: String?
let dict = NSDictionary()

What is the practical difference between the following

9条回答
  •  孤城傲影
    2020-11-29 17:48

    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:)

提交回复
热议问题