How to access @Published var from func outside of view?

I'm trying to remove the logic from the view, while keeping the benefits of SwiftUI. Idea 1 works but it makes use of an extra variable than I would want to. Idea 2 gives error: Property wrappers are not yet supported on local properties. What is the best way of making this work? Many thanks.

import Combine
import Foundation
import SwiftUI

// Model

enum Model: String, RawRepresentable {

    case foo = "foo"
    case bar = "bar"
}

// State

var data1: String = Model.foo.rawValue

class State: ObservableObject {

    @Published internal var data2: String = data1
}

// Logic

func logic() {

// Idea 1: OK

    //data1 = Model.bar.rawValue
    //print(State().data2)

// Idea 2: Error Property wrappers are not yet supported on local properties

    @ObservedObject let state = State()
    state.data2 = Model.bar.rawValue
    print(state.data2)
}

// View

struct bar: View {

    @EnvironmentObject private var state: State

    internal var body: some View {
    
        logic()
        return Text(verbatim: self.state.data2)
    }
}

@ObservedObject is for the View to keep track if the value triggers willChange publisher. Since you're not inside a View, there's not need to use it (and you'll need to subscribe to that publisher manually).

1 Like