Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Inheritance

Swift Inheritance

Inheritance is the core capability that distinguishes classes from structs and enums: one class can acquire the properties, methods, and subscripts of another class.

The class that is inherited from is called the parent class (also superclass or base class), and the class that inherits is called the subclass.

Besides using the parent class's members directly, a subclass can override them or add its own new members.

In Swift, only classes support inheritance; structs and enums do not, which has been compared in 《Swift Structs》.


Base Class and Subclass

A class that is not inherited by any other class is called a base class; in Swift there is no need to explicitly write a root parent class as in Java.

RunoobEmployee below is a base class with two stored properties, name and salary, and a describe() method.

Example

import Foundation

// Base class: a class that does not inherit from any other class

class

RunoobEmployee

{

    var name

:

String

    var salary

:

Double

    init

(

name

:

String, salary

:

Double

)

{

        self.

name

=

name

        self.

salary

=

salary

   

}

    func describe

(

)

String

{

       

return

"(name)'s monthly salary is (salary)"

   

}

}

// Subclass: inherits RunoobEmployee and adds its own stored properties

class

RunoobManager

:

RunoobEmployee

{

    var bonus

:

Double

    init

(

name

:

String, salary

:

Double, bonus

:

Double

)

{

        self.

bonus

=

bonus                      

// First initialize the subclass's own stored properties

        super.

init

(

name

:

name, salary

:

salary

)

 

// Then call the parent class initializer

   

}

    func totalIncome

(

)

Double

{

       

return

salary

12

bonus

   

}

}

let employee

=

RunoobEmployee

(

name

:

"Xiao Ming"

, salary

:

8000

)

print

(

employee.

describe

(

)

)

let manager

=

RunoobManager

(

name

:

"Xiao Hong"

, salary

:

15000

, bonus

:

30000

)

print

(

manager.

describe

(

)

)

         

// Call the method inherited from the parent class

print

(

"Annual income: (manager.totalIncome())"

)

Running result:



小明 的月薪是 8000.0

小红 的月薪是 15000.0

年收入:210000.0

The key to subclass syntax is writing a colon after the class name followed by the parent class name, with multiple protocols or parent classes separated by commas.

A subclass instance can directly read the parent class's salary, showing that inherited members are visible to the subclass.

Initialization Order Cannot Be Reversed

In a subclass initializer, you must first assign values to the stored properties it introduces, and then call super.init.

Reversing the order and calling super.init first causes a compile error: the subclass's properties have no initial values yet, and Swift does not allow an object to be in a half-initialized state.

These rules are part of the two-phase initialization process; for details, see 《Swift Initialization》。


Overridden method

If a subclass is not satisfied with a parent class method's implementation, it can override it with the override keyword.

Example

import Foundation

class

RunoobStaff

{

    var name

:

String

    init

(

name

:

String

)

{

self.

name

=

name

}

    func duty

(

)

String

{

       

return

"(name): completes daily development tasks"

   

}

}

class

RunoobLeader

:

RunoobStaff

{

   

// override indicates this is an override of a parent class method

    override func duty

(

)

String

{

        let base

=

super.

duty

(

)

 

// First call the parent class's implementation

       

return

base

", and is responsible for team management"

   

}

}

print

(

RunoobLeader

(

name

:

"Xiao Hong"

)

.

duty

(

)

)

Running result:



小红:完成日常开发任务,并负责团队管理

The signature of an overridden method must match the parent class's exactly, including the method name, parameter types, and return type.

Note:Forgetting to write override will cause a compile error; conversely, writing override when the parent class has no such method will also cause an error. Both errors are caught by the compiler for you — don't rely on runtime to discover them.


Overriding Properties

Properties can also be overridden, in two common ways: adding observers to an inherited property, or overriding a computed property.

Adding Property Observers to Inherited Properties

Regardless of whether the property is stored or computed in the parent class, the subclass can attach willSet / didSet to it by overriding it.

Example

import Foundation

class

RunoobAccount

{

    var balance

:

Double

=

0

}

class

RunoobSavingsAccount

:

RunoobAccount

{

   

// Override the parent class's stored property to add property observers

    override var balance

:

Double

{

        didSet

{

           

// Triggered after each assignment; oldValue is the value before this write

            print

(

"Balance updated to (balance), change this time (balance - oldValue)"

)

       

}

   

}

}

let account

=

RunoobSavingsAccount

(

)

account.

balance

=

100

account.

balance

=

250

Running result:



余额已更新为 100.0,本次变动 100.0

余额已更新为 250.0,本次变动 150.0

Note that both outputs appear after the assignment; assigning the initial value 0 to balance in the initializer did not trigger the observers.

Note:This is "overriding (override) a property", not "overloading a property". Properties have no parameter lists, so there is no such thing as overloading them.

Overriding Computed Properties

A parent class's computed property can be given a different set of computation logic in the subclass.

Example

import Foundation

class

RunoobShape

{

    var name

:

String

{

"Shape"

}

    var detail

:

String

{

"This is a (name)"

}

}

class

RunoobCircle

:

RunoobShape

{

   

// To override a read-only computed property, just provide get

    override var name

:

String

{

"Circle"

}

}

print

(

RunoobCircle

(

)

.

detail

)

Running result:



这是一个圆形

The parent class's detail calls name, and name is overridden by the subclass, so the final result is "This is a Circle".

This shows that property access is also dynamically dispatched: as long as the subclass provides a new implementation, reads of that property in the parent class's code will also reach the subclass version.

When overriding a read-only computed property, write only get; a read-only property can be overridden as read-write, but overriding a read-write property as read-only is not allowed.

In addition, a stored property declared with let cannot be overridden, since a constant is fixed after initialization.


Accessing super

Overriding is not "starting from scratch"; often a subclass wants to reuse the parent class's implementation and then add to it, and that is when you use super.

The syntax for super is similar to self, but the types of members accessed differ, and so does the syntax.

Accessed object Syntax Description
Parent class method super.duty() Method calls use parentheses
Parent class property super.doubled Properties have no parentheses
Parent class subscript super[index] Accessed with square brackets
Parent class initializer super.init(...) Can only be called in a subclass initializer

The example below focuses on the syntax for properties: there are no parentheses after super.doubled.

Example

import Foundation

class

RunoobCounter

{

    var count

:

Int

=

0

    var doubled

:

Int

{

count

2

}

}

class

RunoobLoggedCounter

:

RunoobCounter

{

    override var doubled

:

Int

{

       

// super.doubled accesses a parent class property; properties have no parentheses

        let parentValue

=

super.

doubled

        print

(

"Parent computed result is (parentValue)"

)

       

return

parentValue

1

   

}

}

let counter

=

RunoobLoggedCounter

(

)

counter.

count

=

5

print

(

counter.

doubled

)

Running result:



父类计算结果是 10

11

Note:super.doubled is a property access; writing it as super.doubled() will cause a compile error. Only methods need parentheses; properties and subscripts do not.


Overriding Subscripts

A subscript is essentially a piece of access code with parameters and can be overridden in the same way; the syntax is to add override before subscript.

The example below overrides the parent class's subscript, changing out-of-bounds access from a crash to returning a placeholder.

Example

import Foundation

class

RunoobList

{

    var items

:

[

String

]

=

[

"a"

,

"b"

,

"c"

]

    subscript

(

index

:

Int

)

String

{

        get

{

items

[

index

]

}

        set

{

items

[

index

]

=

newValue

}

   

}

}

class

RunoobSafeList

:

RunoobList

{

    override subscript

(

index

:

Int

)

String

{

        get

{

           

// Return a placeholder when out of bounds, rather than crashing the program

           

if

index

<

0

||

index

=

items.

count

{

return

"Out of bounds"

}

           

return

super

[

index

]

       

}

        set

{

           

if

index

=

0

&&

index

<

items.

count

{

                super

[

index

]

=

newValue

           

}

       

}

   

}

}

let list

=

RunoobSafeList

(

)

print

(

list

[

1

]

)

print

(

list

[

10

]

)

list

[

0

]

=

"runoob"

print

(

list

[

0

]

)

Running result:



b

越界

runoob

When overriding a subscript, the number of parameters, parameter types, and return type must match the parent class's.

A read-only subscript can be overridden as a read-write subscript, but a read-write subscript cannot be overridden as read-only.

For the complete syntax of subscripts, you can refer to 《Swift Subscripts》。


Preventing Overrides: final

If you do not want a method, property, or subscript to be changed by a subclass, mark it with final.

Example

import Foundation

// final on a class means the entire class cannot be inherited

final

class

RunoobUtility

{

    func run

(

)

{

print

(

"Utility class method"

)

}

}

class

RunoobBase

{

    final func run

(

)

{

print

(

"This method cannot be overridden"

)

}

 

// A single method is forbidden from being overridden

    func config

(

)

{

print

(

"This method can be overridden"

)

}

}

class

RunoobDerived

:

RunoobBase

{

    override func config

(

)

{

print

(

"Subclass overridden config"

)

}

}

RunoobUtility

(

)

.

run

(

)

RunoobDerived

(

)

.

run

(

)

RunoobDerived

(

)

.

config

(

)

Running result:



工具类的方法

这个方法不允许被重写

子类重写的 config

If you insist on overriding a final method, the compiler will stop you directly:



error: instance method overrides a 'final' instance method

Likewise, inheriting from a final class also produces an error.

Besides expressing design intent, final has an added benefit: knowing that a method will not be overridden, the compiler can switch to static dispatch, saving the cost of table lookup.

Note:final's "not allowing cross-module inheritance" and the access-control open are two different things; open governs the combination of visibility and inheritability, see 《Swift Access Control》。


Common questions

Below are a few frequently asked questions about inheritance.

Can a subclass inherit the parent class's initializers?

Conditionally. If the subclass does not define any designated initializers, it automatically inherits all of the parent class's designated initializers.

If the subclass implements all of the parent class's designated initializers (whether written by itself or inherited), it additionally inherits the parent class's convenience initializers.

Once the subclass defines its own designated initializer, this automatic inheritance no longer applies, and you need to arrange the initializers yourself.

Can a subclass access the parent class's private members?

No. The scope of private is the lexical scope in which the declaration appears, plus extensions in the same file.

Even if the subclass is written in the same file as the parent class, it does not belong to this scope; a broader fileprivate or internal is required.

Can structs inherit?

No. Structs are value types and do not support inheritance, nor do they have the concept of a parent class.

When shared implementation is needed, structs usually use protocols and protocol extensions instead, see 《Swift Protocol Extensions and Protocol-Oriented Programming》。

Are overridden properties and overridden methods dispatched the same way?

For classes they are the same, both dynamically dispatched, with the call determining which implementation to use based on the instance's actual type.

This is also why a property read in the parent class's code may be the subclass version, as demonstrated by the earlier RunoobShape example.