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?
推荐答案
给定一个类属性,您可以通过在属性声明前加上访问修饰符后跟 get
或 <括号之间的代码>设置代码>.例如,具有公共 getter 和私有 setter 的类属性将声明为:
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
建议阅读:Getter 和 Setter
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屋!