-
InheritanceiOS/Swift 공식문서 2022. 2. 20. 12:21
Defining a Base Class
아무 클래스도 상속받지 않는 클래스를 base class라고 한다. Swift의 경우 Java 등과는 달리 universal한 base class는 없다. 그래서 따로 상속받는 클래스를 명시하지 않으면 base 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을 통해 기존 클래스의 특성을 상속받고, 새로운 특성을 추가할 수 있다. 다음과 같이 콜론 뒤에 superclass 이름을 명시하면 된다.
class Bicycle: Vehicle { var hasBasket = false }
상속된 프로퍼티 값을 수정하거나 이용할 수 있다.
let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 15.0 print("Bicycle: \(bicycle.description)") // Bicycle: traveling at 15.0 miles per hour
Overriding
superclass에게 상속받은 메서드를 재정의하는 것을 말한다. 오버라이딩하려는 메서드의 경우
override
라는 키워드를 사용해야 한다. 실수로 오버라이딩을 해서 예상치 못한 동작을 하는 것을 방지하기 위해서이다.Accessing Superclass Methods, Properties, and Subscripts
메서드를 오버라이딩할 때 superclass에서의 기존 구현을 사용하는 것이 유용한 경우가 있다. 이를 위해
super
키워드를 사용할 수 있다.a.
someMethod()
의 경우 부모 클래스의someMethod()
를 호출하려면super.someMethod()
를 호출하면 된다.
b.someProperty
라는 프로퍼티의 경우super.someProperty
로 접근하면 된다.
c. superclass의 subscript의 경우super[someIndex]
로 접근할 수 있다.Overriding Methods
다음과 같이
override
키워드를 사용하여 오버라이딩이 가능하다.class Train: Vehicle { override func makeNoise() { print("Choo Choo") } } let train = Train() train.makeNoise() // Prints "Choo Choo"
Overriding Properties
프로퍼티를 오버라이딩을 하는 목적은 subclass에서 getter와 setter를 재정의하거나, 프로퍼티 옵저버를 추가하기 위해서이다.
Overriding Property Getters and Setters
stored/computed property 모두 오버라이딩을 하여 subclass에서 getter와 setter를 정의할 수 있다. superclass에서의 stored/computed 여부는 subclass가 알지 못한다. 다만 프로퍼티의 이름과 타입만 알 뿐이다. 컴파일러가 오버라이딩한 프로퍼티가 superclass의 프로퍼티와 매치되는지 확인할 수 있게 하기 위해서, 오버라이딩하는 프로퍼티의 이름과 타입 모두 명시해야 한다.
read-only property를 read-write로 오버라이딩하는 것은 가능하지만, read-write를 read-only로 오버라이딩하는 것을 불가능하다.
note
오버라이딩에서 setter를 제공했다면, getter도 오버라이딩해야 한다. getter를 수정하고 싶지 않다면 단순히
super.someProperty
를 반환하면 된다.예시
다음은
Vehicle
클래스의description
프로퍼티를 오버라이딩한 예시이다.class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear \(gear)" } } let car = Car() car.currentSpeed = 25.0 car.gear = 3 print("Car: \(car.description)") // Car: traveling at 25.0 miles per hour in gear 3
Overriding Property Observers
상수인 stored property이거나, read-only computed property가 아니라면, property observer를 추가할 수 있다. 다음 예시의 경우
Car
에서의currentSpeed
가 옵저버를 가지고 있지 않지만,AutomaticCar
에서 getter를 추가한 것을 관찰할 수 있다.class AutomaticCar: Car { override var currentSpeed: Double { didSet { gear = Int(currentSpeed / 10.0) + 1 } } } let automatic = AutomaticCar() automatic.currentSpeed = 35.0 print("AutomaticCar: \(automatic.description)") // AutomaticCar: traveling at 35.0 miles per hour in gear 4
Preventing Overrides
subclass에서의 오버라이딩을 방지하기 위해서는 superclass에서 멤버에
final
키워드를 작성하면 된다. 클래스 전체를final
로 선언하여 클래스 안의 모든 멤버가 오버라이딩되는 것을 방지할 수도 있다.Reference
https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html
'iOS > Swift 공식문서' 카테고리의 다른 글
Deinitialization (0) 2022.02.21 Initialization (0) 2022.02.21 Subscripts (0) 2022.02.19 Methods (0) 2022.02.19 Properties (0) 2022.02.18