Is there a way to make an Object conform to Codable that has an array of other Objects?
I got following Object:
struct Album: Identifiable, Codable {
let id = UUID()
let name: String
let artist: String
let songs: [AlbumSong]
let releaseDate: Date
let price: Int
let albumImageUrl: String
var unlocked: Bool
}
I try to fetch my Data from firebase Database and create an Album but it needs to conform to Codable. I guess the problem is the array of AlbumSong
@State var albums: [Album] = []
FirebaseManager.shared.firestore.collection("songs").getDocuments { querySnapshot, error in
if let error = error {
print(error)
return
}
guard let documents = querySnapshot?.documents else {
return
}
self.albums = documents.compactMap { document -> Album? in
do {
return try document.data(as: Album.self)
} catch {
return nil
}
}
My firebase Database looks like this:
This is what AlbumSong looks like:
struct AlbumSong: Identifiable {
let id = UUID()
let title: String
let duration: TimeInterval
var image: String
let artist: String
let track: String
}
CodePudding user response:
To use Codable
all properties of the type also have to be codable. Most of the Swift primitive types (String
,Int
,....) do. For your Album
to conform you have to conform AlbumSong
to Codable
struct AlbumSong: Identifiable, Codable {
let id = UUID()
let title: String
let duration: TimeInterval
var image: String
let artist: String
let track: String
}