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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.