🔸Self

╱🚧 under construction

swifttypeinheritance ⟩ Self

// superclass
class BasePoint {

    var x: Double
    var y: Double
    
    required init(x: Double, y: Double) {
        self.x = x
        self.y = y
    }
    
    func duplicate() -> Self {
        // ⭐️ `Self` 指「真正執行此方法的物件」的「型別」,例如:
        //  • basePoint.duplicate()   :Self 指 BasePoint
        //  • coloredPoint.duplicate():Self 指 ColoredPoint
        return Self(x: x, y: y)    // ⭐️ 注意:這裡 Self 是大寫❗️
    }
}

// subclass
class ColoredPoint: BasePoint {

    var color: String
    
    // (convenience init)
    required convenience init(x: Double, y: Double) {
        // ⭐️ 注意:這裡 self 是小寫❗️
        // (convenience init 指派初始化任務給自己的 designated init)
        self.init(x: x, y: y, color: "black")
    }
    
    // (designated init)
    required init(x: Double, y: Double, color: String = "black") {
        self.color = color
        super.init(x: x, y: y)
    }
}

// BasePoint instaces
let a1 = BasePoint(x: 1, y: 2)
let a2 = a1.duplicate()

// ColoredPoint instances
let b1 = ColoredPoint(x: 3, y: 4, color: "red")
let b2 = b1.duplicate() // ⭐️ 執行繼承來的方法

print(type(of: a2))     // ⭐️ BasePoint
print(type(of: b2))     // ⭐️ ColoredPoint

Last updated

Was this helpful?