【问题标题】:how to create variable property in protocol where as {get set} for one class and {get} for another class如何在协议中创建变量属性,其中一个类的 {get set} 和另一个类的 {get}
【发布时间】:2020-12-09 02:01:39
【问题描述】:
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}。但我需要在两个类中使用相同的属性。

【问题讨论】:

  • 那你总不能设置mustBeSettable吧?如果您有 SomeProtocol 类型的变量 x。当xStage2 的一个实例时,当您执行x.mustBeSettable = "something" 时,您期望会发生什么?
  • 创建两个协议 - 一个只需要 { get },另一个从第一个继承,并且还需要 { get set }... 或者,为了避免潜在的 X-Y 问题 - 解释你的'实际上正在努力实现
  • 你的设计是错误的。协议就像一个合同。如果并不总是需要属性设置器(可选),您需要从协议声明中删除 set var mustBeSettable: String { get } 顺便说一句,您的属性命名没有任何意义,因为您已经说过它可能无法设置。跨度>

标签: swift swift-protocols protocol-oriented


【解决方案1】:

可能的解决方案是按相反的顺序进行,在协议级别将最初设为只读(否则将无法满足协议要求):

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-06
    • 2023-03-18
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多