Now that Paul touched on UserDefaults in one of the latests HWS+ articles, I have a related question:
I’d like to store in UserDefaults an IndexPath value representing a selection in a collection view. Ideally I would like to store a nil value too in case there’s nothing selected.
I was thinking of going for something like this:
extension IndexPath {
func asData() -> Data? {
do {
let encoder = PropertyListEncoder()
let data = try encoder.encode(self)
return data
}
catch {
return nil
}
}
}
and then:
let index = IndexPath(item: 0, section 0)
UserDefaults.standard.set(index.asData(), forKey: “SomeKey”)
Disclaimer: I know that accepting nil as stored value is probably not the best solution so I could handle that case with a fictitious index that would represent a no-selection case, for instance:
IndexPath(item: -1, section: -1)
My question is:
Are there any other method for encoding objects into property lists? Would .encode(to: Encoder) work? Which Encoder should I use there?