Downcast upcast using as! as?

demo

http://stackoverflow.com/questions/29637974/whats-the-difference-between-as-as-and-as
http://stackoverflow.com/questions/27570957/swift-difference-as-string-vs-as-string

Setup

Animal

MeatEater

VeggieEater

Upcast

upcast

The upcast, going from a derived class to a base class, can be checked at compile time and will never fail.

Upcast Example

Downcast

A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type with a type cast operator (as? or as!).

Because downcasting can fail, the type cast operator comes in two different forms. The conditional form, as?, returns an optional value of the type you are trying to downcast to. The forced form, as!, attempts the downcast and force-unwraps the result as a single compound action.

Use the conditional form of the type cast operator (as?) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.

Downcast example

1) To start off, we have a bunch of MeatEaters and VeggieEaters lying around in the heap.

2) We then have an array of Animal reference (base class) pointing to subclasses VeggieEater or MeatEater. We can do this because both VeggieEater and MeatEater are child class of Animal.

3) When we loop through this array of Animals, we need to know whether this Animal reference is a VeggieEater or MeatEater. Essentially, we need to know whether that animal is a meat or veggie eater. In order to do this, we downcast it to MeatEater and VeggieEater.

downcast

as? Type means: cast to this type, if possible, otherwise evaluate to nil
as! Type means: cast to an optional Type, because I know it’s an optional Type. I understand that if it’s not that, a runtime exception is generated