as! vs as operator in Xcode 6.3 in Swift

前端 未结 3 1782
长情又很酷
长情又很酷 2021-01-29 08:23

Swift changed a lot with Xcode 6.3. I had to replace dozens of places in each of my app as -> as!. Why, what are the rules now?

3条回答
  •  粉色の甜心
    2021-01-29 09:12

    The practical difference is this:

    var optionalString = dict.objectForKey("SomeKey") as? String
    

    optionalString will be a variable of type String?. If the underlying type is something other than a String this will harmlessly just assign nil to the optional.

    var optionalString = dict.objectForKey("SomeKey") as! String?
    

    This says, I know this thing is a String?. This too will result in optionalString being of type String?, but it will crash if the underlying type is something else.

    The first style is then used with if let to safely unwrap the optional:

    if let string = dict.objectForKey("SomeKey") as? String {
        // If I get here, I know that "SomeKey" is a valid key in the dictionary, I correctly
        // identified the type as String, and the value is now unwrapped and ready to use.  In
        // this case "string" has the type "String".
        println(string)
    }
    

提交回复
热议问题