Inheritance | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5429279-programming-in-swift-functions-and-types/lessons/38

Hi Catie,

I noticed that when down-casting, this only works for Marty because he was originally initialised as a StudentAthlete prior to being up-cast to Student and then down-cast to StudentAthlete again. Whereas trying to down-cast anyone else, e.g. Jane as StudentAthlete causes an error, even though she is initialised with the same parameters (firstName, lastName) as StudentAthlete takes.

Please could you explain this behaviour?

Thanks!

P.S. loving the content so far! :smiley:

2 Likes

Hi! Thanks for your question.

With casting, you aren’t making any changes to the properties of an instance. So, for example, you can’t turn Jane into a StudentAthlete. It does look like Jane is initialized with the same properties as a StudentAthelete, but actually, a StudentAthlete is initialized with an isEligible property that a regular Student like Jane doesn’t have. isEligible is a computed property, so it doesn’t appear in the initializer.

Classes are reference types, so, if you said

let student = jane as Student

student is referencing the same thing in memory as jane.

When you cast, you’re asking (or telling!) the compiler to treat one type like another type. You can always cast up to a superclass, but you can’t always cast down to a subclass.

In practice, you’ll be using down casting in cases more like the getEveningActivity function, where you are dealing with a superclass that has multiple possible subclasses, and you want to do something different for a particular subclass. You’ll also see downcasting in cases where you need to subclass types in a framework you didn’t write, like UIKit.