Custom Object in UserDefaults : Swift

Suneet Agrawal
2 min readApr 13, 2022

--

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.

This post was originally posted at https://agrawalsuneet.github.io/blogs/custom-object-in-userdefaults-swift/ and reposted on Medium on 13th April 2022.

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.

/// A type that can convert itself into and out of an external representation.
///
/// `Codable` is a type alias for the `Encodable` and `Decodable` protocols.
/// When you use `Codable` as a type or a generic constraint, it matches
/// any type that conforms to both protocols.
public typealias Codable = Decodable & Encodable

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.

//MARK :- Employee
struct Employee: Codable {
let employeeId: Int
let name, department: String
}
// OR//MARK :- Employee
struct Employee: Codable {
let employeeID: Int
let name, department: String
enum CodingKeys: String, CodingKey {
case employeeID = "employeeId"
case name, department
}
}

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.

--

--