I have two classes, Radio and Podcast, children of the Media class. I'm trying to save an array of Media (with radios and podcasts) to UserDefaults but when I get it back, I only have medias (I'm losing information of Radio or Podcast). I cannot cast the items to Radio or Podcast.
private func saveRecentMediaInData(_ medias:[Media]) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(medias) {
UserDefaults.standard.setValue(encoded, forKey: recentMediasKey)
}
}
private func getRecentMediasFromData() -> [Media] {
let defaults = UserDefaults.standard
if let data = defaults.value(forKey: recentMediasKey) as? Data {
let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Array.self, from: data) as [Media] {
return decoded
}
}
return []
}
Thanks
The issue is not related to
UserDefaults. It's having an array of mixed object to decode withCodable.In this case, a solution is to use a
enumwith associated value:Here is a full sample code: