didSet for a @Binding var in Swift

Instead of didSet you can always use onReceive (iOS 13+) or onChange (iOS 14+): import Combine import SwiftUI struct ContentView: View { @State private var counter = 1 var body: some View { ChildView(counter: $counter) Button(“Increment”) { counter += 1 } } } struct ChildView: View { @Binding var counter: Int var body: some View … Read more

SwiftUI – make sure to publish values from the main thread (via operators like receive(on:)) on model updates

Just put @MainActor before defining your class that is supposed to act in the main thread. And it’s so simple in terms of using new Swift concurrency. @MainActor class DocumentsViewModel: ObservableObject { … } There’s a lot of information about that in new WWDC 2021 videos or articles like that: Using the MainActor attribute to … Read more

Error: Initializer ‘init(_:)’ requires that ‘Binding’ conform to ‘StringProtocol’

Use the @Published property wrapper in your Service class, rather than didChange, and iterate over the indices of service.items like so: struct Item: Identifiable { var id: String var label: String var isOn: Bool { didSet { // Added to show that state is being modified print(“\(label) just toggled”) } } } class Service: ObservableObject … Read more

How can I unwrap an optional value inside a binding in Swift?

You can use this initialiser, which seems to handle this exact case – converting Binding<T?> to Binding<T>?: var body: some View { AvatarView(userData: Binding($userById[activeUserId])!) } I have used ! to force unwrap, just like in your attempts, but you could unwrap the nil however you want. The expression Binding($userById[activeUserId]) is of type Binding<UserData>?.

Accessing ViewModel field in SwiftUI using Xcode 12: “Accessing State’s value outside of being installed on a View”

Thanks to @Andrew’s answer I figured out how to make it work again. First you change the @State to @Published: @Published public var amount: Int = 1 Next, you need to change how your Picker is bound to the data: Picker(selection: $model.amount, label: Text(“Amount”)) { Text(“€1”).tag(1) Text(“€2”).tag(2) Text(“€5”).tag(5) Text(“€10”).tag(10) }.pickerStyle(SegmentedPickerStyle()) So we went from model.$amount … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)