Casting in Swift 1.2: a brief summary
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, useas
when the compiler can type-check that the conversion is valid; and Swift won’t compile aas
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 isnil
if the conversion fails. If you write anas?
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, useas!
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).” Likeas?
, the compiler will warn you if you write anas!
cast which it knows will always fail.