Search code examples
swiftreactive-swift

ReactiveSwift mutable property with read only public access


I have a class with enum property state. This property's value (by value I mean ReactiveSwift.Property's value) needs to be accessed and observed by other classes, but value change should be private. Currently it is implemented in a such way:

enum State {
    case stopped, running, paused
}

var state: Property<State> {
    return Property(mutableState)
}
fileprivate let mutableState = MutableProperty<State>(.stopped)

This pattern allows me to modify mutableState property within class file. At the same time outside the class state is available only for reading and observing.

The question is whether there is a way to implement a similar thing using single property? Also probably someone can suggest a better pattern for the same solution?


Solution

  • I can't think of any way to do this with a single property. The only adjustment I would make to your code is to make state a stored property rather than a computed property that gets newly created each time it is accessed:

    class Foo {
        let state: Property<State>
    
        fileprivate let mutableState = MutableProperty<State>(.stopped)
    
        init() {
            state = Property(mutableState)
        }
    }