Optional state with shared properties

I couldn't find an example of this, and I'm not sure this is the best way to do it:

I want to have a specific part of the app that needs some piece of optional state while at the same time has to access parts of the global state. In order not to check for the optional part to be there in every case of the reducer I would like to make that whole state optional and use the optional operator on Reducer.

The problem is, the examples on optional state always deal with state that doesn't share any properties that need to bubble back to the global state.

To be able to do this I'm using a backing property. How does this look? Is there a better option?

struct LocalState {
    internal var internalProperty: String
    var sharedProperty: String
}

struct AppState {
    var sharedProperty: String

    var _localState: LocalState?
    var localState: LocalState? {
        get {
            if _localState == nil {
                return nil
            }

            var copy = _localState!
            copy.sharedProperty = sharedProperty
            return copy
        }
        set {
            _localState = newValue
            sharedProperty = newValue!.sharedProperty
        }
    }
}
1 Like