在 Swift 中给出以下内容:
var optionalString: String?
let dict = NSDictionary()
以下两个陈述之间的实际区别是什么:
optionalString = dict.objectForKey("SomeKey") as? String
vs
optionalString = dict.objectForKey("SomeKey") as! String?
实际的区别是这样的:
var optionalString = dict["SomeKey"] as? String
optionalString
将是一个类型的变量String?
。如果基础类型不是 aString
这将无害地分配nil
到可选的。
var optionalString = dict["SomeKey"] as! String?
这说的是,我know这个东西是一个String?
。这也将导致optionalString
存在类型String?
, but如果底层类型是其他类型,它将崩溃。
然后使用第一种样式if let
安全地打开可选的包装:
if let string = dict["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".
print(string)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)