3 回答

TA貢獻1966條經驗 獲得超4個贊
as關鍵字用于進行上下轉換:
// Before Swift 1.2
var 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.2
var aView: UIView = someView()
var tableView = aView as! UITableView
感嘆號清楚地表明您知道自己在做什么,并且如果您不小心混淆了各種類型,很可能事情會變得非常糟糕!
一如既往 使用可選綁定是最安全的方法:
// This isn't new to Swift 1.2, but is still the safest way
var aView: UIView = someView()
if let tableView = aView as? UITableView {
// do something with tableView
}
從以下站點獲得此消息:SOURCE

TA貢獻1829條經驗 獲得超6個贊
as
在Swift 1.2及更高版本中,as只能用于向上轉換(或消除歧義)和模式匹配:
// 'as' for disambiguation
let width = 42 as CGFloat
let block = { x in x+1 } as Double -> Double
let something = 3 as Any? // optional wrapper can also be added with 'as'
// 'as' for pattern matching
switch item {
case let obj as MyObject:
// this code will be executed if item is of type MyObject
case 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 UIButton
let label = subviews.first as! UILabel

TA貢獻1853條經驗 獲得超9個贊
可以正確執行您想要的操作的正確習慣(在所有Swift版本中,至少到并包括1.2)是as?可選的強制轉換。
if let width = imageDetails["width"] as? Int
可選的強制類型轉換返回一個可選的(在這種情況下為Int?),并在運行時進行測試。您的原始代碼可能將強制轉換為可選類型。
- 3 回答
- 0 關注
- 947 瀏覽
添加回答
舉報