Book Image

Learning Swift

By : Andrew J Wagner
Book Image

Learning Swift

By: Andrew J Wagner

Overview of this book

Table of Contents (18 chapters)
Learning Swift
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Classes


A class can do everything that a structure can; except that, a class can use something called inheritance. A class can inherit the functionality from another class and then extend or customize its behavior. Let's jump straight to some code.

Inheriting from another class

First, let's define a class called Building that we can inherit from later:

class Building {
    let squareFootage: Int

    init(squareFootage: Int) {
        self.squareFootage = squareFootage
    }
}
var aBuilding = Building(squareFootage: 1000)

Predictably, a class is defined using the class keyword instead of struct. Otherwise, a class looks extremely similar to a structure. However, we can also see one difference here. With a structure, the initializer we created earlier would not be necessary because it would be created for us. With classes, initializers are not automatically created unless all the properties have default values.

Now let's look at how to inherit from this building class:

class House: Building {
...