加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:10:44 所属栏目:百科 来源:网络整理
导读:在Swift中给出以下内容: var optionalString: String?let dict = NSDictionary() 以下两个语句之间的实际区别是什么: optionalString = dict.objectForKey("SomeKey") as? String vs optionalString = dict.objectForKey("SomeKey") as! String? 实际的区
在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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读