Inherit & extension inheritance and extension
Parent class
Class Car {
var speed = 0
var Description: String {
Return "mph" (speed) km/h
}
Func sound () {
}
}
Let a car = car ()
A car. Description
Subclass Inherits Parent Class
Class Bike: Car {
var has basket = False
}
Let a bike = bicycle ()
A bike. There is a basket = True
a bike. Speed = 25
A bike. Description
Subclasses of subclasses
Class couple bike: Bike {
var current number of passengers = 0
}
Let a couple bike = couple bike ()
A couple bike. Speed = 20
A couple bike. Description
Methods for subclasses overloading parent classes
Class bullet train: Car {
Override Func beep () {
println ("Toot Toot")
}
}
Let a bullet train = car ()
A bullet train. Sound ()
The subclass overloads the computed properties of the parent class
Class Car: Car {
Override var speed = 60
Number of var wheels = 0
Override var Description: string{
Return super. Description + ", have \ (number of wheels) of wheels"
}
Override var speed: int{
Didset {
If speed > 120 {
println ("Warning: You are speeding")
}
}
}
}
Let a car = car ()
A car. Speed = 121
A car. Number of wheels = 4
A car. Description
Extension (equivalent to classification)
The class/struct/enum type that already exists. Typically used to
1. Source code agnostic situation
2. Decomposition of complex classes to improve maintainability
Extension Double {
var rmb:double{
return self * 0.0597
}
}
31_4150.rmb
Integer self squared
Extension Int {
mutating func squared () {
Self *= Self
}
}
var an integer = 1024
An integer. Square ()
An integer
Swift Inheritance and extension