DEV Community

Darko Dujmovic
Darko Dujmovic

Posted on

Using bindings to connect SwiftUI view with view model based on a protocol with property wrapper requirement

Let's try to make a MVVM based SwiftUI feature that has a Toggle element.

We'll make our Model, View and ViewModel. To make our ViewModel easily replaceable for DI we'll define it in our View as a protocol.

Let's start, create a new SwiftUI Project and you should have your ContentView as this

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Enter fullscreen mode Exit fullscreen mode

Ok, let's create a new file and call it ContentViewViewModel that will look like this

import Foundation

struct ContentViewViewModel {

}
Enter fullscreen mode Exit fullscreen mode

Let's get back to our View and add a reference to our ViewModel
private let viewModel = ContentViewViewModel()

Our view will look like:

import SwiftUI

struct ContentView: View {

    private let viewModel = ContentViewViewModel()

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)