UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

3      

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 :-)

5      

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.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.