为什么允许我使用继承所述协议的结构设置协议的只读 属性?

Why am I allowed to set a read only property of a protocol using a struct that inherits said protocol?

我正在学习一个关于面向协议的编程范例的教程,其中我对一些我认为相当简单的东西感到困惑,它是协议或 getter 和 setter 的只读属性。我的理解是,只读 属性 是通过在协议中声明变量时使用关键字 'get' 来表示的。我很兴奋,所以我很快编写代码创建了一个游乐场,看看我的想法是否准确,但似乎我仍然可以更改我认为只读的 属性。我做错了什么让它成为真正的只读 属性 到我无法设置它的地方?

protocol FullName {
    var firstName: String {get set}
    var lastName: String {get set}
    var readOnlyProperty: String {get}

}

struct OuttaBeerOuttaHere: FullName {
    var firstName: String

    var lastName: String

    var readOnlyProperty: String = "Jack! Jack!...Line from Titanic"

}

var leonardoDicaprio = OuttaBeerOuttaHere.init(firstName: "Leonardo", lastName: "Dicaprio", readOnlyProperty: "WTF")

print(leonardoDicaprio.readOnlyProperty) //prints "WTF"

leonardoDicaprio.readOnlyProperty = "what now"

print(leonardoDicaprio.readOnlyProperty) //prints "what now"

来自 Docs

Here’s an example of a protocol with a single instance property requirement:

protocol FullyNamed {
    var fullName: String { get }
}

The FullyNamed protocol requires a conforming type to provide a fully-qualified name. The protocol doesn’t specify anything else about the nature of the conforming type—it only specifies that the type must be able to provide a full name for itself. The protocol states that any FullyNamed type must have a gettable instance property called fullName, which is of type String

这是协议的要求,不是定义

您的协议未将 readOnlyProperty 声明为只读 属性。它只要求该协议的实现至少具有可获取的 readOnlyProperty 属性。是否允许 属性 的突变取决于实现本身。

What am I doing wrong to make it a true read only property to where I can't set it?

协议(一组规则)和采用协议的类型(即您的结构)之间存在差异。

  • 你的协议规则说 readOnlyProperty 应该是可读的。

  • 您的结构通过使其可读来服从,使其可写。这不是非法的,所以一切都很好 — 结构中的 readOnlyProperty 是可读写的。

是非法的,但相反,即协议声明 属性 可读写,但采用者声明它是只读的。你的例子中没有出现这种情况,但如果出现了,编译器就会阻止你。