NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Encoding objects for UserDefaults

Forums > Swift

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?

   

I dont think saving IndexPath is a good idea. You should store either the item directly or some other identifier that will always identify it correctly. Because with IndexPath you need to make sure that the item will always be on the same IndexPath which does not seem realistic.

Also using Data is overkill because IndexPath is just a two integers :-)

2      

Thanks Filip! Interesting points.

I actually need to store both the item and the section, so before I started really thinking about this, I was indeed storing the two integer values separately in UserDefaults.

I will try to hide in an extension the construction and deconstruction to and from IndexPath so that it just takes one line of code to set it in UserDefaults. I'll post my results here later on.

   

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.