Swift and SwiftUI community!

I'm relatively new to Swift and SwiftUI, and I've encountered a challenge with two-way binding that I hope you can help me resolve.

I have an @Observable class named ObservableClass defined in a separate file (ObservableClass.swift):

//  ObservableClass.swift

import Foundation

@Observable class ObservableClass {
    var textFieldString = "Initial Value"
}

In the main app file (ObservableBindingApp.swift), I create an instance of ObservableClass with the @State property wrapper and expose it to different views through the environment:

// ObservableBindingApp.swift

import SwiftUI

@main
struct ObservableBindingApp: App {
    @State var observableClass = ObservableClass()
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(observableClass)
        }
    }
}

Now, in ContentView.swift, I want to bind the textFieldString property of observableClass—retrieved from the environment using @Environment—to the text property of a TextField view. I've attempted this by prefixing the property with a $ sign:

//  ContentView.swift

import SwiftUI

struct ContentView: View {
    @Environment(ObservableClass.self) var observableClass: ObservableClass
    var body: some View {
        VStack {
            Text(observableClass.textFieldString)
            TextField("Write something", text: $observableClass.textFieldString)
        }
    }
}

#Preview {
    ContentView()
        .environment(ObservableClass())
}

However, I'm encountering the following error:

"Cannot find '$observableClass' in scope."

And when I omit the $ sign, I get:

"Cannot convert value of type 'String' to expected argument type 'Binding<String>'."

How can I successfully establish a two-way binding between a property in an @Observable class and the @Binding property of an object? It's crucial to note that the @Observable class must be accessed from the environment using @Environment.

Your guidance would be greatly appreciated! Thanks in advance!

0

There are 0 best solutions below