swift中的self屬性

這裏寫圖片描述
Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.
每個類型的實例都有一個隱式的屬性self,它實際上相當於實例它自己。以應用self屬性在它的實例方法中引用當前的實例。
注意:是在實例方法中引用它自己。
因此上邊的方法也可以這樣寫:
這裏寫圖片描述
In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter.
實際上,你並不需要經常在你的代碼中寫self。如果你不顯示的寫self,swift假定你正在引用的是當前實例的屬性或者方法,無論你什麼時候應用已知的屬性或者方法。
The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.
設置self屬性的主要目的是爲了當方法中的參數和實例的屬性有相同名字時使用。在這種情況下,參數優先,用一種更加合理的方式來引用屬性時非常必要的。你應用self來區分參數名和屬性名。
這裏寫圖片描述

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