# Self

[swift](https://lochiwei.gitbook.io/ios/swift) ⟩ [type](https://lochiwei.gitbook.io/ios/swift/type) ⟩ [inheritance](https://lochiwei.gitbook.io/ios/swift/type/inheritance) ⟩ Self&#x20;

{% hint style="success" %}

* 在 [protocol](https://lochiwei.gitbook.io/ios/swift/type/category/protocol) 的定義中：<mark style="color:blue;">`Self`</mark> 指<mark style="color:yellow;">遵循該協定的具體型別</mark> (<mark style="color:orange;">concrete type</mark>)。
* 在 [class](https://lochiwei.gitbook.io/ios/swift/type/category/basic/class) 的定義中：<mark style="color:blue;">`Self`</mark> 指<mark style="color:yellow;">該物件的具體型別</mark>，例如：當一個定義在 <mark style="color:blue;">`class A`</mark> 中的方法(<mark style="color:orange;">method</mark>) 裡面如果提到 <mark style="color:blue;">`Self`</mark>，那麼這個 <mark style="color:blue;">`Self`</mark> 不一定指 <mark style="color:blue;">`A`</mark>，因為如果一個子類別 (<mark style="color:orange;">subclass</mark>) <mark style="color:blue;">`class B`</mark> 的物件 (透過[繼承](https://lochiwei.gitbook.io/ios/swift/type/inheritance)的方式) 執行這個方法時，<mark style="color:blue;">`Self`</mark> 指的是 <mark style="color:blue;">`B`</mark>。
  {% endhint %}

{% tabs %}
{% tab title="💈範例" %}
{% tabs %}
{% tab title="1" %}

```swift
// 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
```

{% endtab %}

{% tab title="2" %}

```swift
// swift
let b = 2
```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="📘 手冊" %}

* [Swift](https://docs.swift.org/swift-book/documentation/the-swift-programming-language) ⟩ [Inheritance](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/inheritance/)&#x20;
  {% endtab %}
  {% endtabs %}
