學習 Swift 的過程中,我們可能很容易忽略了定義 class method 時,其實有分為 Instance Method 與 Type Method。

<aside> 💡 由於我認為 實例instance 很差的翻譯方式,所以所有的文章中,都會直接以英文表示。

</aside>

<aside> 💡 Struct 同樣也有分Instance Method 與 Type Method。為了方便說明,這篇都以 class 作為討論的標的。

</aside>

兩者最主要的差異在於,是否需要有 Instance才可以呼叫。

顧名思義,Instance Method 會使用到這個 class instance 中的變數,或是這個method會跟instance 綁定在一起(對這個instance做事情等)。

而 Type Method,則是無關乎這個 instance 本身,或是不需要使用到這個class instance 當中的變數。

以下可以看到範例

// Instance Method 範例
class ExampleClass {
    var property: String
    
    init(property: String) {
        self.property = property
    }
    
    func displayProperty() {
        print("Property is \\(property)")
    }
}

// 下方呼叫displayProperty之前一定要有instance
let exampleInstance = ExampleClass(property: "Hello, world!")
exampleInstance.displayProperty()  // Output: Property is Hello, world!

class AnotherClass {
    static func typeMethod() {
        print("This is a static type method, not dependent on an instance.")
    }
    class func typeMethod() {
        print("This is a class type method, not dependent on an instance.")
    }
}

// 下方typeMethod呼叫之前不需要有AnotherClass的instance,這個method 可以直接取用。
AnotherClass.typeMethod() 

Instance Method Type Method
主要差異 Instance Methods are linked to a particular instance of a class, struct, or enum. They typically operate on the data that belongs individually to each object. Type Methods (marked with static or class) are linked to the class itself rather than to any object instance. They can be called without creating an instance of the class.
宣告方式 在 Class 中直接宣告的都是 instance Method 如果要宣告為Type Method,則需要在前面加上 class 或是 static
override 在 Class 中宣告的 function 是可以被繼承並且被override的 在 class 中宣告的 type function,只有class 標記的可以被override,static不能被override。
使用時機 Use instance methods when the method needs to access or modify the state of an object (instance). Use type methods when the method is relevant to all instances of the class or when no instances are needed to perform the method's function.