Chapter 7. Classes, Actors, and Inheritance: Inheritance Is Always a Thing

image

Structs showed us how useful it can be to build custom types. But Swift has a number of other tricks up its sleeve, including classes. Classes are similar to structs: they let you make new data types that have properties and methods within them. However, in addition to being reference types—instances of a specific class share a single copy of their data (unlike structs, which are value types and get copied)—classes support inheritance. Inheritance allows one class to build upon the features of another.

A struct by any other name (that name: a class)

A class is very similar to a struct, with a few important differences:

image
image
image

If your class has properties, then you must create an initializer. So, yes, if it has properties.

When you’re writing your class, if you include any properties at all, then you need to provide an initializer.

So, if you wrote a class to represent types of plants, like this:

image

You ...

Get Head First Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.