Swift只读外部,读写内部属性 [英] Swift readonly external, readwrite internal property
问题描述
在Swift中,定义公共模式的常规方式是什么,在该模式中,属性是外部只读的,但可以由拥有该属性的类(和子类)在内部进行修改.
In Swift, what is the conventional way to define the common pattern where a property is to be externally readonly, but modifiable internally by the class (and subclasses) that own it.
在Objective-C中,有以下选项:
In Objective-C, there are the following options:
- 在接口中将该属性声明为只读,并使用类扩展名在内部访问该属性.这是基于消息的访问,因此可以很好地与KVO,原子性等配合使用.
- 在接口中将该属性声明为只读,但在内部访问后备ivar.由于对ivar的默认访问受到保护,因此在类层次结构中效果很好,在该类层次结构中,子类也可以修改值,但该字段为只读.
在Java中,约定为:
In Java the convention is:
- 声明一个受保护的字段,并实现一个公共的只读getter(方法).
Swift的成语是什么?
What is the idiom for Swift?
推荐答案
给定一个类属性,您可以通过在属性声明前面加上access修饰符并在括号之间使用get
或set
来指定不同的访问级别.例如,具有公共获取器和私有设置器的类属性将声明为:
Given a class property, you can specify a different access level by prefixing the property declaration with the access modifier followed by get
or set
between parenthesis. For example, a class property with a public getter and a private setter will be declared as:
private(set) public var readonlyProperty: Int
建议阅读: Martin关于可访问性级别的考虑仍然有效-即没有protected
修饰符,internal
仅限制对模块的访问,private
仅对当前文件的访问,以及public
没有限制.
Martin's considerations about accessibility level are still valid - i.e. there's no protected
modifier, internal
restricts access to the module only, private
to the current file only, and public
with no restrictions.
2个新的访问修饰符fileprivate
和open
,而对private
和public
进行了一些修改:
2 new access modifiers, fileprivate
and open
have been added to the language, while private
and public
have been slightly modified:
-
open
仅适用于类和类成员:它用于允许对类进行子类化或在定义它们的模块之外重写成员.public
而是使类或成员可公开访问,但不能继承或覆盖
open
applies to class and class members only: it's used to allow a class to be subclassed or a member to be overridden outside of the module where they are defined.public
instead makes the class or the member publicly accessible, but not inheritable or overridable
private
现在使成员仅从封闭的声明中可见并可以访问,而fileprivate
到包含该成员的整个文件
private
now makes a member visible and accessible from the enclosing declaration only, whereas fileprivate
to the entire file where it is contained
更多详细信息这里.
这篇关于Swift只读外部,读写内部属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!