Wednesday, November 11, 2026
HomeiOS Developmentios - How do I get a "Binding" from my mannequin to...

ios – How do I get a “Binding” from my mannequin to my View in Swift?

[ad_1]

I am pretty new to Swift and I am already operating issues. From my understanding, it’s good observe to separate the app into Fashions that describe the info, Views that show stuff and permit for consumer enter, and ViewModels that translate the consumer’s intents into knowledge modification and permits the view to react accordingly.

That being mentioned, I set out on doing a quite simple app utilizing that logic.
So I create a mannequin file that goes like:

import Basis

struct MyModel {
    var testData: Double
    ...
}

then a viewModel that appears like this;

import Basis

class MyViewModel: ObservableObject {
    @Printed var myModel = MyModel(testData: 0)

    func setTest(_ newVal: Double) {
        splitModel.testData = newVal
    }

    ...
}

and eventually my view:

struct ContentView: View {
    @ObservedObject var viewModel = MyViewModel()

    var physique: some View {
        NavigationView {
            Type {
                Part {
                    TextField("Hi there", worth: viewModel.splitModel.quantity, format: .forex(code: "USD"))
                }
            }
        }
    }
}

And this does not work as a result of viewModel.splitModel.quantity is not a Binding however a straight up Double. The one manner I discovered to repair that’s to simply put the info within the view with @State, so precisely what I used to be making an attempt to keep away from by getting this file construction.

I’d love an evidence of the logic I am alleged to implement to make it work, and perhaps get corrected about my comprehension of Swift.
Thanks upfront !

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments