Swift协议只能设置吗? [英] Swift Protocol get only settable?
问题描述
为什么我可以做到这一点而没有任何错误:
why can I do this without any error:
var testDto = ModelDto(modelId: 1)
testDto.objectId = 2
在我定义这个的时候:
protocol DataTransferObject {
var objectType: DtoType { get }
var parentObjectId: Int { get set }
var objectId: Int { get }
var objectName: String { get set }
}
struct ModelDto: DataTransferObject {
var objectType: DtoType
var parentObjectId: Int
var objectId: Int
var objectName: String
init(modelId: Int) {
self.objectType = DtoType.Model
self.objectId = modelId
self.parentObjectId = -1
self.objectName = String()
}
}
如果协议中的定义大多被忽略(getter,setter定义),为什么我仍然要使用它们?
If the definition in my protocol is mostly ignored (getter, setter definition), why should I use them anyway?
推荐答案
The getter and setter requirements can be satisfied by a conforming type in a variety of ways. If a property declaration includes both the get and set keywords, a conforming type can implement it with a stored variable property or a computed property that is both readable and writeable (that is, one that implements both a getter and a setter). However, that property declaration can’t be implemented as a constant property or a read-only computed property. If a property declaration includes only the get keyword, it can be implemented as any kind of property.
这篇关于Swift协议只能设置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!