1. Origin πŸ‘©β€πŸ’»

Stored Properties λ₯Ό μ œμ™Έν•œ Properties 의 Overriding 은 Overriding Properties 에 ν¬μŠ€νŒ… λ˜μ–΄μžˆλ‹€.

Stored Properties 의 Overriding λ§Œμ„ 보기 μœ„ν•΄ λ‹€λ₯Έ characteristics λŠ” μ œμ™Έν•˜κ³  tag ν•˜λ‚˜λ§Œ 갖도둝 μˆ˜μ •ν–ˆλ‹€.

class Vehicle {
    var tag = "Vehicle"
}

class Bicycle: Vehicle {
}

class Tandem: Bicycle {
}
var vehicle = Vehicle()
var bicycle = Bicycle()
var tandem = Tandem()

print(vehicle.tag)  // Vehicle
print(bicycle.tag)  // Vehicle
print(tandem.tag)   // Vehicle

Bicycle, Tandem 은 Vehicle λ₯Ό μƒμ†ν•˜μ˜€κΈ° λ•Œλ¬Έμ— tag κ°€ λͺ¨λ‘ β€œVehicle”이닀.


2. Overriding Stored Properties πŸ‘©β€πŸ’»

1. Overriding stored properties - Fail

class Vehicle {
    var tag = "Vehicle"
}

class Bicycle: Vehicle {
    override var tag: String = "Bicycle"    // Cannot override with a stored property 'tag'
}

λ‹€λ₯Έ Properties 와 λ§ˆμ°¬κ°€μ§€λ‘œ override modifier λ₯Ό μ‚¬μš©ν•΄ λ™μΌν•˜κ²Œ Stored Properties λ₯Ό μž¬μ •μ˜ν•˜λ € ν–ˆμœΌλ‚˜ Swift λŠ” Overriding λΆˆκ°€λŠ₯ν•˜λ‹€λŠ” μ—λŸ¬λ₯Ό 좜λ ₯ν•œλ‹€.

2. Implement computed properties with private stored properties - Success

Property Wrappers λ₯Ό κ΅¬ν˜„ν• λ•Œ 처럼 Subclass μ—μ„œ Computed Properties 와 Private Stored Properties λ₯Ό λ§Œλ“€μ–΄ 마치 Stored Properties λ₯Ό μ‚¬μš©ν•˜λŠ” κ²ƒμ²˜λŸΌ κ΅¬ν˜„ν•΄ ν•΄κ²°ν•  수 μžˆλ‹€.

class Vehicle {
    var tag = "Vehicle"
}

class Bicycle: Vehicle {
    private var _tag = "Bicycle"
    override var tag: String {
        get { _tag }
        set { _tag = newValue }
    }
}

class Tandem: Bicycle {
    private var _tag = "Tandem"
    override var tag: String {
        get { _tag }
        set { _tag = newValue }
    }
}
var vehicle = Vehicle()
var bicycle = Bicycle()
var tandem = Tandem()

print(vehicle.tag)  // Vehicle
print(bicycle.tag)  // Bicycle
print(tandem.tag)   // Tandem

3. Use Phase 2 of Initialization - Success

사싀 μœ„ 2번 방법이 1번 방식을 μ‚¬μš©ν•  수 μ—†μ–΄ Stack Overflow κ²€μƒ‰μ—μ„œ λ‚˜μ˜¨ λ‹΅λ³€μ΄μ—ˆλ‹€.

ν•˜μ§€λ§Œ docs.swift.org λ₯Ό κ³΅λΆ€ν•˜λ©΄μ„œ 사싀 Swift Initialization에 λŒ€ν•œ μ •ν™•ν•œ μ΄ν•΄λ§Œ μžˆλ‹€λ©΄ μ‰½κ²Œ ν•΄κ²°ν•  수 μžˆλ‹€λŠ” 것을 μ•Œκ²Œλ˜μ—ˆλ‹€.
λ°”λ‘œ Initialization Phase 2의 μˆ˜μ •ν•  기회λ₯Ό μ‚¬μš©ν•˜λŠ” 것이닀.

class Vehicle {
    var tag = "Vehicle"
}

class Bicycle: Vehicle {
    override init() {
        super.init()
        tag = "Bicycle"
    }
}

class Tandem: Bicycle {
    convenience init(tag: String) {
        self.init()
        self.tag = tag
    }
}
var vehicle = Vehicle()
var bicycle = Bicycle()
var tandem = Tandem(tag: "Tandem")

print(vehicle.tag)  // Vehicle
print(bicycle.tag)  // Bicycle
print(tandem.tag)   // Tandem

Awesome!! πŸ˜†πŸ˜†




Reference

  1. β€œInheritance.” The Swift Programming Language Swift 5.7. accessed Nov. 30, 2022, Swift Docs Chapter 12 - Inheritance.
  2. β€œInitialization.” The Swift Programming Language Swift 5.7. accessed Dec. 1, 2022, Swift Docs Chapter 13 - Initialization.