Hi! I am currently solving the challenge for Day 61, so I'm adapting my previous work to support SwiftData. My problem is more on the design side than on the coding one.
What I had previously done was to create a UserCollection
Observable class that contained the list of users and a boolean indicating a possible error. I did so because it was then easy to create an initializer that fetches the data only once.
Now, I am finding it a bit hard to adapt this architecture to support SwiftData. What I initially tried (after of course adapting the User
and Friend
classes to be Model
s) was to make the UserCollection
class a Model
too, but I quickly discovered the the @Query
macro only works with arrays and such (from what I understood, or at least I only found examples of this kind). So something like @Query var userCollection: UserCollection
in ContentView
would not work.
So now the obvious solution would be to move the list of users and the download of the data to the ContentView
itself, which would allow me to use the @Query
macro as usual, but I have to say I quite liked the architecture I had sketched out. Is there any possible alternative I'm missing to keep what (to me) is conceptually one thing (a set of users and its related data) together?
I'll attach the original UserCollection
class, which I would like to adapt to SwiftData.
import Foundation
@Observable
class UserCollection {
var users: [User] = []
var downloadError = false
init() {
Task {
do {
print("Downloading...")
let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!
let (data, _) = try await URLSession.shared.data(from: url)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let decodedData = try decoder.decode([User].self, from: data)
self.users = decodedData
} catch {
print("Failed to load the users!")
downloadError = true
}
}
}
}