为什么允许我使用继承了该协议的结构来设置协议的只读属性? [英] Why am I allowed to set a read only property of a protocol using a struct that inherits said protocol?
问题描述
我正在跟踪有关面向协议的编程范例的教程,在该教程中,我被一些我认为很简单的东西感到困惑,这是协议或getter和setter的只读属性.我的理解是,在协议中声明变量时,使用关键字"get"表示只读属性.我很兴奋,所以我迅速编码创建了一个游乐场,以查看我的想法是否正确,但是看来我仍然可以更改我认为是只读的属性.我将其设置为无法设置的只读属性,这是怎么做的?
I'm following a tutorial on the protocol oriented programming paradigm in which I'm confused by something I thought was rather simple which is read only properties of protocols or getters and setters. My understanding is that a read only property is signified by using the keyword 'get' when declaring a variable within a protocol. I was excited so I quickly coded created a playground to see if my thinking was accurate however it appears that I can still change the property which I thought was read only. What am I doing wrong to make it a true read only property to where I can't set it?
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"
推荐答案
要使它成为无法设置的只读属性,我在做错什么?
What am I doing wrong to make it a true read only property to where I can't set it?
采用协议的协议(一组规则)和类型(即您的结构)之间是有区别的.
There is a difference between a protocol (a set of rules) and the type (i.e. your struct) that adopts the protocol.
-
您的协议规则说
readOnlyProperty
应该可读.
您的结构遵循可读性,并且 也使其可写.那不是违法的,所以一切都很好-并且结构中的readOnlyProperty
是可读写的.
Your struct obeys by making it readable, and also makes it writable. That is not illegal, so all is well — and readOnlyProperty
in your struct is read-write.
将会是非法的,这将是相反的,即,协议将属性声明为可读写,而采用者则将其声明为只读.在您的示例中并没有出现这种情况,但是如果出现这种情况,编译器将阻止您.
What would have been illegal would be the inverse, i.e. for the protocol to declare a property read-write but the adopter to declare it read-only. That situation didn't arise in your example, but if it had, the compiler would have stopped you.
这篇关于为什么允许我使用继承了该协议的结构来设置协议的只读属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!