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

前端 未结 9 1690
耶瑟儿~
耶瑟儿~ 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:57

    as? Types - means the down casting process is optional. The process can be successful or not(system will return nil if down casting fails).Any way will not crash if down casting fails.

    as! Type? - Here the process of down casting should be successful (! indicates that) . The ending question mark indicates whether final result can be nil or not.

    More info regarding "!" and "?"

    Let us take 2 cases

    1. Consider:

      let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
      

      Here we don't know whether the result of down casting of cell with identifier "Cell" to UITableViewCell is success or not. If unsuccessful then it returns nil( so we avoid crash here). Here we can do as given below.

      if let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell {
          // If we reached here it means the down casting was successful
      }
      else {
          // unsuccessful down casting
      }
      

      So let us remember it like this - If ? it means we are not sure whether value is nil or not (question mark comes when we don't know things).

    2. Contrast that to:

      let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell. 
      

      Here we tell the compiler that down casting should be successful. If it fails the system will crash. So we give ! when we are sure that value is non nil.

提交回复
热议问题