Instruction

Inheritance

Swift has a preference for structs. It recommends you start by using a struct until you need some feature that’s only available for classes. Inheritance is one of these features — it only works with classes.

Use inheritance to model your app’s data if your objects have some properties in common, but some groups of objects have additional properties and/or specific behaviors. Rather than duplicating common code across all instances, you create subclasses that inherit properties and methods from the parent class. Additionally, you can add properties and methods specific to each subclass.

For example, you could use the Met Museum’s art objects’ classification property to define subclasses of MuseumObject — one subclass for each classification value.

MuseumObject Ceramics Basketry Painting Cypress and Poppies
Museum art object classification tree

The relationship between a subclass and its parent class is an is-a relationship: “Painting is-a MuseumObject”.

Each subclass could have properties that are relevant and useful for that specific classification. A Painting object might have an artistDisplayName property, while a Ceramics object might have a region or excavation property. If a subclass has properties that aren’t in its parent class, you must define an init method that initializes these properties, then calls super.init to initialize the other properties.

Polymorphism

A subclass could also have methods that are relevant and useful for that specific classification. You can override a method in the parent class to do something different, such as using additional properties. Polymorphism translates to “many forms”. It occurs when each subclass object invokes its own version of a method, giving it many forms. You don’t need to write branching code to specify the object’s behavior; each object knows exactly what to do.

In this lesson, you’ll work with a simple example: You’ll create a PublicDomainObject subclass of MuseumObject and override showImage().

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo