“ as?”,“ as!”和“ as”有什么区别?

在升级到Swift 1.2之前,我可以编写以下行:


if let width = imageDetails["width"] as Int?

现在它迫使我写这一行:


if let width = imageDetails["width"] as! Int?

我的问题是,如果我被迫如上所述编写代码,难道我不能只编写下面的代码,它会做同样的事情吗?在imageDetails的所有值中它都会给我相同的结果吗?


if let width = imageDetails["width"] as Int


动漫人物
浏览 740回答 3
3回答

慕标5832272

as关键字用于进行上下转换:// Before Swift 1.2var aView: UIView = someView()var object = aView as NSObject // upcast var specificView = aView as UITableView // downcast从派生类到基类的转换可以在编译时检查,并且永远不会失败。但是,向下转换可能会失败,因为您无法始终确定特定的类别。如果您有UIView,则可能是UITableView或UIButton。如果您的垂头丧气选择正确的类型,那就太好了!但是,如果碰巧指定了错误的类型,则会出现运行时错误,并且应用程序将崩溃。在Swift 1.2中,向下转换必须是可选的as?或用as!“强制失败”。如果您确定类型,则可以用as强制转换!类似于您使用隐式展开的可选内容的方式:// After Swift 1.2var aView: UIView = someView()var tableView = aView as! UITableView感叹号清楚地表明您知道自己在做什么,并且如果您不小心混淆了各种类型,很可能事情会变得非常糟糕!一如既往 使用可选绑定是最安全的方法:// This isn't new to Swift 1.2, but is still the safest wayvar aView: UIView = someView()if let tableView = aView as? UITableView {  // do something with tableView}从以下站点获得此消息:SOURCE

肥皂起泡泡

as在Swift 1.2及更高版本中,as只能用于向上转换(或消除歧义)和模式匹配:// 'as' for disambiguationlet width = 42 as CGFloatlet block = { x in x+1 } as Double -> Doublelet something = 3 as Any?  // optional wrapper can also be added with 'as'// 'as' for pattern matchingswitch item {case let obj as MyObject:    // this code will be executed if item is of type MyObjectcase let other as SomethingElse:    // this code will be executed if item is of type SomethingElse...}as?在有条件的类型转换操作符as?会尝试进行转换,但回报nil,如果它不能。因此,其结果是可选的。let button = someView as? UIButton  // button's type is 'UIButton?'if let label = (superview as? MyView)?.titleLabel {    // ...}as!该as!运算符用于强制类型转换。as!仅当您确定向下转换将始终成功时,才使用类型转换运算符()的强制形式。如果尝试向下转换为错误的类类型,则此形式的运算符将触发运行时错误。// 'as!' for forced conversion.// NOT RECOMMENDED.let buttons = subviews as! [UIButton]  // will crash if not all subviews are UIButtonlet label = subviews.first as! UILabel

暮色呼如

可以正确执行您想要的操作的正确习惯(在所有Swift版本中,至少到并包括1.2)是as?可选的强制转换。if let width = imageDetails["width"] as? Int可选的强制类型转换返回一个可选的(在这种情况下为Int?),并在运行时进行测试。您的原始代码可能将强制转换为可选类型。
打开App,查看更多内容
随时随地看视频慕课网APP