Swift 中协议的只读属性 [英] Read-only properties of protocols in Swift
问题描述
来自Learn the Essentials of Swift"游乐场,有一个示例协议:
From the "Learn the Essentials of Swift" playground, there's an example protocol:
protocol ExampleProtocol {
var simpleDescription: String { get }
func adjust()
}
在这个例子之后有一段短文,内容如下:
There's a short passage after this example that reads:
注意:simpleDescription 属性后面的 { get } 表示它是只读的,意味着该属性的值可以查看,但永远不会改变.
Note: The { get } following the simpleDescription property indicates that it is read-only, meaning that the value of the property can be viewed, but never changed.
另外给出了一个符合这个协议的类的例子:
Additionally an example is given of a class conforming to this protocol:
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
但是这个类是如何符合协议的呢?是什么阻止我改变 simpleDescription
?什么我不明白?
However how does this class conform to the protocol? What's stopping me from mutating simpleDescription
? What don't I understand?
推荐答案
无法在协议中指定您必须具有只读只读属性.您的协议要求 simpleDescription
属性,并且允许但不要求一个 setter.
There's no way to specify in a protocol that you must have a read-only property. Your protocol asks for a simpleDescription
property, and allows but does not require a setter.
另请注意,您可能改变 simpleDescription
的唯一原因是您知道您的 a
属于 SimpleClass
类型.如果我们有一个 ExampleProtocol
类型的变量......
Note also that the only reason you may mutate simpleDescription
is because you know your a
is of type SimpleClass
. If we have a variable of type ExampleProtocol
instead...
var a: ExampleProtocol = SimpleClass()
a.simpleDescription = "newValue" //Not allowed!
这篇关于Swift 中协议的只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!