Search

[Swift 공식 문서] 13. Inheritance

부제
카테고리
Swift
세부 카테고리
공식문서 번역
Combine 카테고리
최종편집일
2022/07/16 15:22
작성중
관련된 포스팅
생성 일시
2022/07/16 14:47
태그
클래스에는 상속이라는 특별한 기능이 존재합니다.
상속을 통해 다른 클래스에게 메서드, 프로퍼티, 기타 다른 특징들을 건네줄 수 있습니다.
상속을 받는 클래스를 subclass
상속을 해주는 클래스를 superclass
라고합니다.
subclass는 superclass 의 메서드, 프로퍼티, 서브 스크립트에 접근 호출이 가능하다.
위 메서드, 프로퍼티, 서브스크립트를 override(덮어쓰기) 하여 커스터마이징도 가능하다.
override 사용시 swift 는 superclass 에 해당 메서드, 프로퍼티, 서브스크립트가 존재하는 지 확인하여 오류를 발견해줍니다.

Defining a 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 } }
Swift
복사
(사실 그냥 클래스,,,)
let someVehicle = Vehicle() print("Vehicle: \(someVehicle.description)") // Vehicle: traveling at 0.0 miles per hour 사용방법 동일
Swift
복사

Subclassing

서브클래스를 만드는 방법은 클래스 이름뒤에 : 과 함께 슈퍼클래스의 이름을 쓰면된다.
class SomeSubclass: SomeSuperclass { // subclass definition goes here }
Swift
복사
동일한 방법으로 앞서 정의한 Vehicle 클래스를 상속해 서브클래스를 만들어보자
class Bicycle: Vehicle { var hasBasket = false }
Swift
복사
새 Bicycle 클래스는 자동으로 Vehicle 클래스의 모든 특징(메서드, 프로퍼티)을 가집니다.
즉 다음과 같은 사용이 가능합니다.
bicycle.currentSpeed = 15.0 print("Bicycle: \(bicycle.description)") // Bicycle: traveling at 15.0 miles per hour
Swift
복사
이렇게 만들어진 서브클래스 또한 다른 클래스의 슈퍼클래스가 될 수 있습니다.
class Tandem: Bicycle { var currentNumberOfPassengers = 0 }
Swift
복사
Tandem 클래스는 Bicycle 클래스의 모든 프로퍼티와 메서드를 상속받습니다.
심지어 Vehicle 의 프로퍼티와 메서드들 까지요!
따라서 아래와 같이 사용이 가능합니다.
let tandem = Tandem() tandem.hasBasket = true tandem.currentNumberOfPassengers = 2 tandem.currentSpeed = 22.0 print("Tandem: \(tandem.description)") // Tandem: traveling at 22.0 miles per hour
Swift
복사

Overriding

override 키워드를 사용해 상속받은 프로퍼티, 메서드, 서브 스크립트를 덮어쓸 수 있습니다!
override 키워드를 사용하면 해당 프로퍼티, 메서드, 서브스크립트가 상위 클래스에 존재하는 지 확인할 수 있습니다.
반대로 상위 클래스에 이미 동일한 이름의 정의가 존재하지만 override 를 사용하지 않은 경우 오류가 발생합니다.

Accessing Superclass Methods, Properties, and Subscripts

상위 클래스의 메서드, 프로퍼티, 서브스크립트를 override 하고자할 때, 상위 클래스에 구현되어 있는 부분을 활용하고 싶을 때가 있습니다.
이럴때는 override 정의 내부에서 super 키워드를 사용하면 됩니다.
super.someMethod() super.someProperty
Swift
복사

Overriding Methods

상속받은 인스턴스 또는 타입 메서드 또한 서브클래스에서 커스터마이징이 가능합니다.
class Train: Vehicle { override func makeNoise() { print("Choo Choo") } }
Swift
복사
이 경우 Train 클래스의 인스턴스를 생성하면 오버라이딩 된 버전의 메서드가 호출됩니다.
let train = Train() train.makeNoise() // Prints "Choo Choo"
Swift
복사

Overriding Properties

상속받은 인스턴스 또는 타입 프로퍼티 또한 오버라이드가 가능하다
이때 getter setter 문 또한 사용이 가능하며,
오버라이드 한 프로퍼티가 원래의 프로퍼티를 변경하는 것을 감지할 수 있다.
class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear \(gear)" } }
Swift
복사

Overriding Property Getters and Setters

computed 프로퍼티든 stored 프로퍼티든 오버라이드 시 getter setter 문을 사용할 수 있다.
getter setter 문 사용시 주의사항이 두가지 있다.
1.
상속받은 프로퍼티가 computed 프로퍼티 인지 stored 프로퍼티인지는 직접 타입을 지정해주어야 한다.
2.
상위 클래스에서 읽기-쓰기 로 선언된 프로퍼티를 서브클래스에서 읽기전용으로 override 할 수 없다.
class Car: Vehicle { var gear = 1 override var description: String { //읽기전용(computed)으로 선언된 모습 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
Swift
복사

Overriding Propety Observers

프로퍼티 옵저버 또한 오버라이드할 수 있습니다.
상위 클래스에 프로퍼티 옵저버가 존재하지 않더라도 오버라이드를 통해 추가할 수 있습니다.
프로퍼티가 상위클래스에 정의되어 있든 하위 클래스에 정의 되어있는지와는 상관 없이 프로퍼티 값 변화를 감지합니다.
상수로 선언된 stored 프로퍼티에는 프로퍼티 옵저버를 오버라이드할 수 없습니다.
상위클래스의 프로퍼티인 currentSpeed 를 override 해 옵저버를 추가한 모습입니다.
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
Swift
복사

Preventing Overrides

final 키워드를 사용하면 프로퍼티, 타입 프로퍼티, 메서드가 오버라이드 되는 것을 방지할 수 있습니다.
프로퍼티, 타입 프로퍼티, 메서드 앞에 final 만 작성하면 됩니다.
(예 : final varfinal funcfinal class func, and final subscript )
전체 클래스의 상속 자체를 불가능하게 할 수 있습니다.
final 키워드를 class 선언 앞에 작성해주면 됩니다.