在Swift中向下转换可选内容:as?类型,还是一样!类型? [英] Downcasting optionals in Swift: as? Type, or as! Type?
问题描述
在Swift中提供以下内容:
Given the following in Swift:
var optionalString: String?
let dict = NSDictionary()
以下两个语句之间的实际区别是什么?
What is the practical difference between the following two statements:
optionalString = dict.objectForKey("SomeKey") as? String
vs
optionalString = dict.objectForKey("SomeKey") as! String?
推荐答案
实际的区别是:
var optionalString = dict["SomeKey"] as? String
optionalString
将是类型为String?
的变量.如果基础类型是String
以外的其他类型,则只需将nil
分配给可选类型即可.
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["SomeKey"] as! String?
这说,我知道这东西是String?
.这也会导致optionalString
的类型为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.
然后将第一种样式与if let
一起使用以安全地打开可选的包装:
The first style is then used with if let
to safely unwrap the optional:
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)
}
这篇关于在Swift中向下转换可选内容:as?类型,还是一样!类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!