首页 > 解决方案 > 如何在协议中创建变量属性,其中一个类的 {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}。但我需要在两个类中使用相同的属性。

标签: swiftswift-protocolsprotocol-oriented

解决方案


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

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

推荐阅读