gpt4 book ai didi

swift - Swift 中协议(protocol)的只读属性

转载 作者:搜寻专家 更新时间:2023-10-31 08:12:00 25 4
gpt4 key购买 nike

在“Learn the Essentials of Swift” Playground 中,有一个示例协议(protocol):

protocol ExampleProtocol {
var simpleDescription: String { get }
func adjust()
}

这个例子之后有一小段内容是:

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.

另外给出了一个符合这个协议(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

但是这个类如何符合协议(protocol)呢?是什么阻止我改变 simpleDescription?我不明白什么?

Playground screenshot

最佳答案

无法在协议(protocol)中指定您必须具有只读的only 属性。您的协议(protocol)要求 simpleDescription 属性,并且允许但不要求 setter。

另请注意,您可以改变 simpleDescription 的唯一原因是因为您知道您的 aSimpleClass 类型。如果我们有一个 ExampleProtocol 类型的变量......

var a: ExampleProtocol = SimpleClass()
a.simpleDescription = "newValue" //Not allowed!

关于swift - Swift 中协议(protocol)的只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31358518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com