NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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 Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

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.