在Swift中转换可选项:as?类型或作为!类型?

在Swift中给出以下内容
var optionalString: String?
let dict = NSDictionary()

以下两个语句之间的实际区别是什么:

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

vs

optionalString = dict.objectForKey("SomeKey") as! String?
实际的区别是:
var 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)
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...