0%

Swift as? 与 as! 的区别

var dict = [Int:Any]()
dict[1] = 15

let x = dict[1] as? String
print(x) // nil because dict[1] is an Int

let zz = dict[1] as! String // crashes because a forced downcast fails


dict[2] = "Yo"

let z = dict[2] as! String?
print(z) // optional("Yo")
let z2 = dict[2] as! String
print(z2) // exactly String


let m = dict[3] as! String?
print(m) // nil. the forced downcast succeeds, but dict[3] has no value

警告 Treating a forced downcast to ‘NSNumber’ as optional will never produce ‘nil’
提示 Fix-it use ‘as?’ to perform a conditional downcast to ‘NSNumber’