Swift中协议的只读属性

tra*_*m_3 4 swift

从"学习Swift的基本知识"游乐场,有一个示例协议:

protocol ExampleProtocol {
    var simpleDescription: String { get }
    func adjust()
}
Run Code Online (Sandbox Code Playgroud)

在这个例子后面有一段短文,内容如下:

注意:simpleDescription属性后面的{get}表示它是只读的,这意味着可以查看属性的值,但从不更改.

另外,给出了符合该协议的类的示例:

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
Run Code Online (Sandbox Code Playgroud)

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

游乐场截图

and*_*n22 11

有没有办法,你必须有一个只读的协议指定唯一的财产.您的协议要求提供simpleDescription属性,并允许不需要设置器.

另请注意,您可能会发生变异的唯一原因simpleDescription是因为您知道自己a的类型SimpleClass.如果我们有一个类型的变量ExampleProtocol而不是......

var a: ExampleProtocol = SimpleClass()
a.simpleDescription = "newValue" //Not allowed!
Run Code Online (Sandbox Code Playgroud)