Class 는 다른 class 에서 method/property/ 다른 특징을 상속할 수 있음.

Defining a Base Class

Base class : 다른 class 에서 상속받지 않은 class

Swift class 는 universal base class 에서 상속받고 이렇지 않고 직접 정의한 클래스는 자동으로 다른 class 가 상속할 수 있는 base class 가 됨

아래 클래스는 다른 class 가 받을 수 있는 공통의 특징을 정의하고 있음

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    func makeNoise() {
        // do nothing - an arbitrary vehicle doesn't necessarily make a noise
    }
}

Subclassing

Subclassing : 이미 존재하는 class 를 기반으로 하는 동작.

Subclass 는 이미 존재하는 class 에서 특징을 상속받음. Subclass 에 새로운 특징을 추가할 수도 있음

// subclass 이름 다음에 superclass 이름을 써서 상속받는 것을 표시
class SomeSubclass: SomeSuperclass {
    // subclass definition goes here
}

// subclass Bicycle
// 자동으로 Vehicle 의 특성을 모두 얻음 e.g. currentSpeed / description / makeNoise()
class Bicycle: Vehicle { 
	var hasBasket = false // 상속받은 특징에 추가로 직접 정의한 property
}

let bicycle = Bicycle() 
bicycle.hasBasket = true

bicycle.currentSpeed = 15.0 // 상속받은 property 수정
print("Bicycle: \(bicycle.description)") 
// Bicycle: traveling at 15.0 miles per hour

Subclass 자체도 subclassed 될 수 있음

class Tandem: Bicycle {
    var currentNumberOfPassengers = 0
}

Overriding

Subclass 는 superclass 에서 상속받은 instance method / type method / instance property / type property / subscript 에 custom 구현을 제공할 수 있음.

상속받은 특징을 override 하려면 override 키워드를 prefix 로 붙이면 됨. 이를 통해 superclass 에 일치하는 부분이 없는 definition 을 실수로 overriding 하는 것을 방지함. 키워드가 없는 경우 compiler 에러 발생

Accessing Superclass Methods, Properties, and Subscripts

Subclass 에 method / property / subscript override 를 할 경우, 이미 존재하는 superclass 구현을 override 내부에서 사용하는 게 도움이 될 때가 있음.

super prefix 를 써서 superclass 의 method/property/subscript 에 접근할 수 있음

Overriding Methods

상속받은 instance / type method 를 override 해서 subclass 에서 다르게 구현할 수도 있음

class Train: Vehicle {
    override func makeNoise() {
        print("Choo Choo")
    }
}

let train = Train()
train.makeNoise()
// Prints "Choo Choo".

Overriding Properties

상속받은 instance / type property 를 override 해서 custom getter / setter 를 제공하거나 property observer 를 추가해서 값 변화를 추적할 수도 있음

Overriding Property Getters and Setters

상속받은 property 가 stored / computed property 와는 상관 없이 custom getter/setter 를 제공할 수 있음. Subclass 에서는 상속받은 property 가 computed 인지 stored 인지는 모름 - 상속받은 property 가 특정 이름과 type 이 있다는 것만 앎.

Read-only property 를 상속받아서 read-write property 로 만들 수는 있지만 read-write property 를 상속받아서 read-only property 로 만들 수 없음

Property 를 override 할 때 setter 를 제공한다면 무조건 getter 도 함께 제공해야 함. 상속받은 property 의 값을 getter 를 사용해서 수정하고 싶지 않다면 super.someProperty 로 상속 받은 값을 전달하는 방식이 있음.

class Car: Vehicle {
    var gear = 1
    override var description: String {
        return super.description + " in gear \(gear)"
    }
}

Overriding Property Observers

상속받은 property 에 property observer 를 추가할 수 있음.

상속받은 constant stored property 나 상속받은 read-only computed property 에는 property observer 를 추가할 수 없음. 이런 property 의 값들은 수정될 수 없기 때문에 willSet 이나 didSet 구현이 어울리지 않음

같은 property 에 overriding setter, overriding property observer 를 동시에 추가할 수 없음. 만약 property 값의 변경을 추적하고 싶고, 이미 해당 property 에 custom setter 를 제공하고 있는 경우 해당 setter 를 사용해서 property observer 가 하는 역할을 수행할 수 있음

class AutomaticCar: Car {
    override var currentSpeed: Double {
        didSet {
            gear = Int(currentSpeed / 10.0) + 1
        }
    }
}

Preventing Overrides

final 을 붙여서 method / property / subscript 가 overriden 되는 것을 막을 수 있음.

final 이 붙은 것을 subclass 에서 override 하면 compile time error 발생함.