0
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}。但我需要在两个类中使用相同的属性。

4

1 回答 1

0

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

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
    }
}
于 2020-12-09T05:05:05.870 回答