Custom Object in UserDefaults : Swift

In continuation to my previous blog UserDefaults in Swift, where we understand the basic functionality of UserDefaults, we’ll try to understand today how can we store custom objects in UserDefaults.

UserDefaults provides us with direct functions for storing primitive data types like Int, Double, Bool, and String. But for custom data types, there is no direct way to store them in UserDefaults. But there is a workaround with which we can store the custom object to UserDefaults. Let’s try to understand in detail along with an example.

What are Custom Objects and Codable?

User-defined class or struct objects are known as custom objects. These classes or structs can have any number of properties.

To store them in UserDefaults, we need to implement or confirm Codable to the user-defined class or struct.

Codable is a typealias of Decodable & Encodable protocols. It adds the functionality of Encoding and Decoding to the class or struct.

To implement or confirm the Codable protocol, we can add the protocol and go with coding keys as the variable names or can define our own custom keys according to the need.

Keep in mind that any custom class used inside the Codable class or struct should also confirm the Codable protocol.

How to store custom object in UserDefaults?

Please continue reading at https://agrawalsuneet.github.io/blogs/custom-object-in-userdefaults-swift/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store