Downcasting optionals in Swift: as? Type, or as! Type?

前端 未结 9 1650
耶瑟儿~
耶瑟儿~ 2020-11-29 17:32

Given the following in Swift:

var optionalString: String?
let dict = NSDictionary()

What is the practical difference between the following

9条回答
  •  有刺的猬
    2020-11-29 17:54

    Maybe this code example will help someone grok the principle:

    var dict = [Int:Any]()
    dict[1] = 15
    
    let x = dict[1] as? String
    print(x) // nil because dict[1] is an Int
    
    dict[2] = "Yo"
    
    let z = dict[2] as! String?
    print(z) // optional("Yo")
    let zz = dict[1] as! String // crashes because a forced downcast fails
    
    
    let m = dict[3] as! String?
    print(m) // nil. the forced downcast succeeds, but dict[3] has no value
    

提交回复
热议问题