Swift 物件方法 (Methods)

方法就是關聯到特定型別 (Class, Struct, Enum) 的函式。

實例方法 (Instance Methods)

這些方法屬於特定實例,用來存取和修改實例屬性,或提供相關功能。

class Counter {
    var count = 0
    
    func increment() {
        count += 1
    }
    
    func increment(by amount: Int) {
        count += amount
    }
    
    func reset() {
        count = 0
    }
}

Self 屬性

每個實例都有一個隱含的屬性 self,指向實例本身。通常不需要顯式寫出,除非參數名稱與屬性名稱衝突:

func increment(by count: Int) {
    self.count += count // 右邊是參數 count,左邊是屬性 count
}

在結構與列舉中修改值 (Mutating)

預設情況下,值型別 (Struct, Enum) 的屬性不能在實例方法中被修改。如果你需要修改,必須將方法標記為 mutating

struct Point {
    var x = 0.0, y = 0.0
    
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}

型別方法 (Type Methods)

這些方法屬於型別本身,使用 static 關鍵字 (在 Class 中若允許子類別覆寫則用 class)。

struct LevelTracker {
    static var highestUnlockedLevel = 1
    var currentLevel = 1
    
    static func unlock(_ level: Int) {
        if level > highestUnlockedLevel { highestUnlockedLevel = level }
    }
    
    static func isUnlocked(_ level: Int) -> Bool {
        return level <= highestUnlockedLevel
    }
}

// 呼叫方式
LevelTracker.unlock(5)