我尝试将数组保存[String: Any]
为用户默认值,并且在某些情况下它可以工作,但其他情况则不能。我使用以下内容保存为默认值:
static func savingQueueToDisk(){
let queueDict = App.delegate?.queue?.map({ (track) -> [String: Any] in
return track.dict
})
if let queueDict = queueDict{
UserDefaults.standard.set(queueDict, forKey: App.UserDefaultKey.queue)
UserDefaults.standard.synchronize()
}
}
Queue是一个Track数组,定义如下:
class Track {
var dict: [String: Any]!
init(dict: [String: Any]) {
self.dict = dict
}
var album: Album?{
guard let albumDict = self.dict[AlbumKey] as? [String: Any] else{
return nil
}
return Album(dict: albumDict)
}
var artists: [Artist]?{
guard let artistsDict = self.dict[ArtistsKey] as? [[String: Any]] else{
return nil
}
let artists = artistsDict.map { (artistdict) -> Artist in
return Artist(dict: artistdict)
}
return artists
}
var id: String!{
return self.dict[IdKey] as! String
}
var name: String?{
return self.dict[NameKey] as? String
}
var uri: String?{
return self.dict[URIKey] as? String
}
}
从同一个 API 检索时,我得到了不同的输出
崩溃输出: http ://www.jsoneditoronline.org/?id=cb45af75a79aff64995e01e5efc0e7b6
有效输出: http ://www.jsoneditoronline.org/?id=0939823a4ac261bd4cb088663c092b20