create a view model for a cookie app in swiftui in swift

To create a view model for a cookie app in SwiftUI, you can follow these steps:

  1. Create a new Swift file in your project and name it "CookieViewModel".
  2. Define your view model class and make it conform to the ObservableObject protocol.
main.swift
    import Foundation
    import SwiftUI

    class CookieViewModel: ObservableObject {

    }
95 chars
7 lines
  1. Declare your model properties inside the view model class. In this example, we'll have "allCookies" property which will hold an array of cookies.
main.swift
    struct Cookie: Hashable {
        let name: String
        let description: String
        let price: Double
        let imageName: String
    }
    
    class CookieViewModel: ObservableObject {
        @Published var allCookies: [Cookie] = [
            Cookie(name: "Chocolate Chip", description: "The classic cookie that everyone loves!", price: 1.99, imageName: "chocolate_chip"),
            Cookie(name: "Oatmeal Raisin", description: "A tasty and healthy option!", price: 2.99, imageName: "oatmeal_raisin"),
            Cookie(name: "Sugar Cookie", description: "Great for decorating and adding frosting!", price: 1.49, imageName: "sugar")
        ]
    }
668 chars
15 lines
  1. Create a view that will use the view model to display the list of cookies.
main.swift
    struct CookieListView: View {

        @ObservedObject var viewModel: CookieViewModel
            
        var body: some View {
            NavigationView {
                List(viewModel.allCookies, id: \.self) { cookie in
                    NavigationLink(destination: CookieDetailView(cookie: cookie)) {
                        CookieRowView(cookie: cookie)
                    }
                }
                .navigationBarTitle(Text("Our Cookies"))
            }
        }
    }
494 chars
16 lines
  1. Create your view model instance and pass it to your view.
main.swift
    struct ContentView: View {

        let viewModel = CookieViewModel()
            
        var body: some View {
            CookieListView(viewModel: viewModel)
        }
    }
182 chars
9 lines

With these steps, you have created a simple view model that holds an array of cookies and provides an interface for fetching and updating that data to be used by your view.

gistlibby LogSnag