Pass data to an @Observable model

Overview

  • I have a navigation split view.
  • The detail view contains a model now this model depends on id from the parent view.

Questions

  1. How can I pass data from the parent view and yet create the view in the detail view?
  2. Or should I be pass the model from the parent view, but the problem is the parent view needs to persist model.
  3. Or is there a better approach?

Hi,

in the parent view the data is like this

@State private var value: Int = 1

and in the child view

@Binding var value: Int

In this case, the parent view controls the data, and the child view can use and modify it.

Is that what you mean?

Christian

@ChrisDE Consider the following model

@Observable
class Model {
    let id: Int
    
    init(id: Int) {
        self.id = id
    }
}
  1. Should the model be created in the parent view (as @State property in parent view) and passed to the detail view?

  2. Or should I create model in the detail view (as @State property in the detail view)? But this id needs to come from the parent view.

@ChrisDE

Questions

  1. Should CarDetailViewModel be created in CarDetailView?
  2. Or should CarDetailViewModel be created in ContentView and passed to CarDetailView?

Code

ContentView

struct ContentView: View {
    @State private var selectedCarID: UUID?
    
    var body: some View {
        NavigationSplitView {
            CarListView(selectedCarID: $selectedCarID)
        } detail: {
            if let selectedCarID {
                CarDetailView(carID: selectedCarID)
            }
        }
    }
}

CarListViewModel

@Observable
class CarListViewModel {
    let cars = [
        Car(id: UUID(), name: "aaa"),
        Car(id: UUID(), name: "bbb")
    ]
}

CarListView

import SwiftUI

struct CarListView: View {
    @Binding var selectedCarID: UUID?
    @State var model = CarListViewModel()
    
    var body: some View {
        List(model.cars, selection: $selectedCarID) { car in
            VStack(alignment: .leading) {
                Text(car.name)
                Text("\(car.id)")
            }
        }
    }
}

CarDetailViewModel

@Observable
class CarDetailViewModel {
    let carID: UUID
    
    init(carID: UUID) {
        self.carID = carID
    }
}

CarDetailView

import SwiftUI

struct CarDetailView: View {
    @State private var model: CarDetailViewModel
    
    init(carID: UUID) {
        let model = CarDetailViewModel(carID: carID)
        _model = State(wrappedValue: model)
    }
    
    var body: some View {
        Text("\(model.carID)")
    }
}
Pass data to an @Observable model
 
 
Q