swift中的self属性

来源:互联网 发布:软件开发项目经验总结 编辑:程序博客网 时间:2024/06/08 00:21

这里写图片描述
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来区分参数名和属性名。
这里写图片描述

0 0
原创粉丝点击