swift中的類型方法

定義
Instance methods, as described above, are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method.
實例方法,正如上邊提到的,是那些被實例調用的方法。你也可以定義一些類型自己調用的方法。這種方法被稱作類方法。你可以表明是類方法,在方法前加上static關鍵字。類也可以應用class關鍵字允許子類重寫父類的實現。
這裏寫圖片描述
注意
在oc中,你僅僅可以爲類定義類型方法。在swift中,你可以類型方法爲所有的類,結構體和枚舉。每種類型方法都顯示的由類型來限定應用範圍。
Within the body of a type method, the implicit self property refers to the type itself, rather than an instance of that type. This means that you can use self to disambiguate between type properties and type method parameters, just as you do for instance properties and instance method parameters.
在類型方法內部,隱式的self指的是類型自己而不是實例。這意味着你可以應用self來區分參數還是屬性。
More generally, any unqualified method and property names that you use within the body of a type method will refer to other type-level methods and properties. A type method can call another type method with the other method’s name, without needing to prefix it with the type name. Similarly, type methods on structures and enumerations can access type properties by using the type property’s name without a type name prefix.
大多數情況下,在類方法內部你應用的方法和屬性可以引用其他的方法和屬性。結構體和枚舉也具有同樣的功能。

發佈了74 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章