在Swift中给出以下内容:
var optionalString: String? let dict = NSDictionary()
以下两个语句之间的实际区别是什么:
optionalString = dict.objectForKey("SomeKey") as? String
vs
optionalString = dict.objectForKey("SomeKey") as! String?
实际的区别是:
原文链接:https://www.f2er.com/swift/321380.htmlvar optionalString = dict.objectForKey("SomeKey") as? String
optionalString将是String类型的变量。如果底层类型是除了String之外的其他类型,这将无害地只是分配nil到可选。
var optionalString = dict.objectForKey("SomeKey") as! String?
这说,我知道这是一个字符串。这也会导致optionalString类型为String ?,但是如果底层类型是别的,它会崩溃。
然后使用第一个样式,如果允许安全地打开可选:
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) }