Casting in Swift 1.2: a brief summary

⚠️
This post was automatically migrated from my old blogging software, and I have not reviewed it for problems yet. Please contact me if you notice any important issues.

Swift 1.2, in beta with Xcode 6.3, makes some changes to casting. Here’s how as, as?, and as! work:

  • as is for guaranteed conversions. That is, use as when the compiler can type-check that the conversion is valid; and Swift won’t compile a as cast it can’t verify. A simple example is a cast to a supertype: myViewControllerSubclass as UIViewController.
  • as? is for trying a conversion at runtime. You’ll get an optional which is nil if the conversion fails. If you write an as? cast which the compiler can tell will never work, it’ll warn you “Cast from 'T' to unrelated type 'U' always fails.” but you can still compile and run your program. A simple example might be parsing values from JSON: someJSONValue as? String.
  • as! is for forced conversions. That is, use as! if you need to make a conversion which should always succeed, but which cannot be type-checked. as! will attempt the conversion at runtime and crash with a message like “Could not cast value of type 'T' (0x1066c4040) to 'U' (0x107f1bd30).” Like as?, the compiler will warn you if you write an as! cast which it knows will always fail.