有沒有辦法使物件符合具有其他物件陣列的 Codable?
我得到以下物件:
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
}
我嘗試從 firebase 資料庫中獲取我的資料并創建一個相冊,但它需要符合 Codable。我想問題是 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
}
}
我的 firebase 資料庫如下所示:


這是專輯歌曲的樣子:
struct AlbumSong: Identifiable {
let id = UUID()
let title: String
let duration: TimeInterval
var image: String
let artist: String
let track: String
}
uj5u.com熱心網友回復:
要使用Codable該型別的所有屬性也必須是可編碼的。大多數 Swift 原始型別 ( String, Int,....) 都可以。為了使您符合,Album您必須符合AlbumSongCodable
struct AlbumSong: Identifiable, Codable {
let id = UUID()
let title: String
let duration: TimeInterval
var image: String
let artist: String
let track: String
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/505218.html
標籤:Google Cloud Collective 迅速 火力基地 谷歌云火库 迅捷
