Class Methods
在 Swift 中, methods 是指 class 裡面的 functions。
在 class 中定義一個 method,定義的方法與定義 function 相同:
所以,當然也可以加入參數:
可以注意到,在 class 中的 method 可以直接存取 class 的 properties,因此在 incrementBy
內可以直接操作 count。
小提醒:跟 class 相反, structre 的 method 不能存取本身的 properties,在 Mutating a Structure 會有更深入的討論。
另外,也可以用 self
這個 keyword,來存取 class 內的 properties:
在上面的程式碼中,因為 resetToCount
這個 method 的參數名稱也叫做 count
,因此我們用 self.count
來分辨我們存取的是 Counter
class 中的 count
property。
下一篇: Structures in Swift