how to create variable property in protocol where as {get set} for one class and {get} for another class

324 Views Asked by At
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
}

in Stage1 class I need access for "mustBeSettable" as {get set}, where as in Stage2 class "mustBeSettable" should be {get} only. but same property I need to use in both classes.

1

There are 1 best solutions below

0
On

The possible solution is to do it in reverse order, make originally read-only at protocol level (otherwise it would not be possible to fulfil protocol requirements):

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