swift - 如何在协议中创建变量属性,其中一个类的 {get set} 和另一个类的 {get}
问题描述
protocol SomeProtocol {
var mustBeSettable: String { get set }
}
class Stage1: SomeProtocol {
//Here "mustBeSettable" should be {get set}
}
class Stage2: SomeProtocol {
//Here "mustBeSettable" should be {get} only
}
在 Stage1 类中,我需要作为 {get set} 访问“mustBeSettable”,而在 Stage2 类中,“mustBeSettable”应该只是 {get}。但我需要在两个类中使用相同的属性。
解决方案
可能的解决方案是以相反的顺序进行,在协议级别使最初为只读(否则将无法满足协议要求):
protocol SomeProtocol {
var mustBeSettable: String { get }
}
class Stage1: SomeProtocol {
var mustBeSettable: String // read-write
init(_ value: String) {
mustBeSettable = value
}
}
class Stage2: SomeProtocol {
let mustBeSettable: String // read-only
init(_ value: String) {
mustBeSettable = value
}
}
推荐阅读
- apache-kafka - Kafka中如何单独安装KSQLdb?
- azure-devops - 模态对话框 Azure Devops 闪烁
- c# - 提取嵌套 Json 数组中的项目
- c# - 当其中一个子实体已附加时,如何将实体附加到上下文?
- javascript - 从数组中提取对象时减少返回 NaN 的函数 - MongoDB 数据库,React 前端
- .net - 使用 Giraffe 登录 Facebook
- c - 在 c 中省略 for 循环的最后一部分
- spring-boot - 使用 Thymeleaf 提交时表单为空
- android - 通用扩展的 Android proguard 规则
- c - C:在数组中找到一对总和为给定数字X的元素