Swift 1.2, in beta with Xcode 6.3, makes some changes to casting. Here’s how
asis for guaranteed conversions. That is, use
aswhen the compiler can type-check that the conversion is valid; and Swift won’t compile a
ascast 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
nilif 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.