Swift - Overriding Stored Properties
Inheritance - Overriding Stored Properties
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
- βInheritance.β The Swift Programming Language Swift 5.7. accessed Nov. 30, 2022, Swift Docs Chapter 12 - Inheritance.
- βInitialization.β The Swift Programming Language Swift 5.7. accessed Dec. 1, 2022, Swift Docs Chapter 13 - Initialization.