I have a struct
called Station
that supports the Codable
protocol. Since it is a struct, it cannot support the NSCoding
protocol. I would like to save an array of these Station
s to the UserDefaults
. I have code that does it without any problems.
func updateRecentStations(stations: [Station]) {
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let data = try! encoder.encode(stationsArray)
UserDefaults.standard.set(data, forKey: "RecentStations")
}
func readRecentStations() -> [Station] {
if let data = UserDefaults.standard.object(forKey: "RecentStations") as? Data {
let stations: [Station] = try! PropertyListDecoder().decode( [Station].self, from: data)
return stations
}
}
These both work. The roundtrip is happening without a problem. But if I examine the <<app>>.plist in Xcode, or call print(Array(UserDefaults.standard.dictionaryRepresentation()))
the displayed data is illegible. The Data
that has been written looks like it is stored in a hexadecimal format. That said, it I open the <<app>>.plist within a text editor, I can see the xml within there, but the .plist isn't meant to be read that way.
The UserDefaults
does not appear to have support for writing a plist to the .plist. Everything works, but because the plist editor can't read what I've written, I feel I am not doing things in the proper way.
Is there a way to support a Codable
being written to the UserDefaults
in such a way that it maintains its structure in a human readable way within there? To be clear, I am looking for a way that replicates the way NSCoding
would add to the NSUserDefaults
hierarchy.