To answer your original question, you can only save certain elements in UserDefaults, and a PersistentIdentifier is not one of them. This type does implement the Codable protocol, so you can use something like JSON encoding/decoding to save to and restore from UserDefaults.
func saveValue(_ newValue: PersistentIdentifier, to store: UserDefaults, at key: String) {
let encoder = JSONEncoder()
store.setValue(try! encoder.encode(newValue), forKey: key)
}
func restoreValue(from store: UserDefaults, at key: String) -> PersistentIdentifier? {
guard let raw = store.data(forKey: key) else {
return nil
}
let decoder = JSONDecoder()
return try? decoder.decode(PersistentIdentifier.self, from: raw)
}
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: