Shall we say you’ve a SwiftUI app, just like the landmarks app, that presently has single Observable class occasion accountable for offering information for the entire app:
@Observable
class ModelData {
var landmarks: [Landmark] = load("landmarkData.json")
var hikes: [Hike] = load("hikeData.json")
var profile = Profile.default
var options: [Landmark] {
landmarks.filter { $0.isFeatured }
}
var classes: [String: [Landmark]] {
Dictionary(
grouping: landmarks,
by: { $0.class.rawValue }
)
}
}
It’s supplied to the app like this:
@important
struct LandmarksApp: App {
@State non-public var modelData = ModelData()
var physique: some Scene {
WindowGroup {
ContentView()
.surroundings(modelData)
}
}
}
And accessed inside particular person elements of the app like this:
@Atmosphere(ModelData.self) var modelData
If we had been to transform this app to SwiftData, we may:
A) Mannequin the Landmark and Hike objects individually by placing “@Mannequin” on each… and eliminating the computed queries and utilizing @Question as an alternative. (Unsure what we might do with Profile since it’s singular)… and share these two separate “mannequin arrays” (?) with the remainder of the app utilizing the approach on this query. On this case, the ModelData class would not exist.
B) OR…. (that is the query)… can we simply put an SwiftData “@Mannequin” on the present ModelData class as an entire, and share it with the whole app? I’ve began attempting to do that, and I’ve bought so far as
@Mannequin
class ModelData {
var landmarks: [Landmark]
var hikes: [Hike]
var profile: Profile
var options: [Landmark] {
landmarks.filter { $0.isFeatured }
}
var classes: [String: [Landmark]] {
Dictionary(
grouping: landmarks,
by: { $0.class.rawValue }
)
}
init(landmarks: [Landmark] = load("landmarks.json"), hikes: [Hike] = load("hikes.json"), profile:Profile = Profile.default) {
self.landmarks = landmarks
self.hikes = hikes
self.profile = profile
}
}
… and it compiles since I made every thing codable… however after I begin fascinated with how I’d edit or replace landmarks my head hurts… and it looks as if possibly it is by no means a good suggestion to make use of this “possibility B.”
Nonetheless, after I proceed with possibility A, I attain some extent the place I notice I’ve misplaced the utility capabilities they usually should be scattered within the codebase.
Are these equally legitimate approaches?