在Swift中向下转换可选内容:as?类型,还是一样!类型? [英] Downcasting optionals in Swift: as? Type, or as! Type?

查看:81
本文介绍了在Swift中向下转换可选内容:as?类型,还是一样!类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆