Website Links

Wednesday 9 December 2015

Swift casting - as! or as?

Today, I'm going to explain the different between "as!" and "as?"

"as!" is appropriate where you know that the underlying type of the object you are trying to cast matches what you are casting to. It will throw an error if it is not the type it expects which may help you avoid overlooking a setup issue or something similar. Whereas "as?" will try to cast it to the type, but if it is not the type it expected then it will return nil. Here's a quick code example:

  // returns an object of type UIImageView?
  // this can be useful in if statements, for if cast is not nil
  // do something with the variable
  let optionalImageView = touches.first?.view! as? UIImageView

  // returns an object of type UIImageView
  // will throw an error if the object is not the expected type
  let optionalImageView = touches.first?.view! as! UIImageView

No comments:

Post a Comment