How to save a structs to UserDefaults in swift

One can save struct, conforming to Codable protocol can be saved to UserDefaults. It’s a very easy and simple task to save Structs to UserDefaults, though inly condition is that your Struct should conform to Codable protocol. As I am assuming you’re aware about Codable protocol and how it has made the task of JSON Serialization and Deserialization in iOS really easy. Thus, I am not going to explain Codable protocol in this blog post.

Saving Struct to UserDefaults

Here we have a two structs, one is cart having items and another struct is for storing out cart items info. Both of our Structs are conforming to Codable protocol.

struct Cart: Codable{
    var items:[CartItem]?

struct CartItem: Codable {
    var ipn: String?
    var shortName:String?
    var longName:String?
    var description:String?
    var thumbnail:String?
    var packaging:String?
    var pricePerUnit:Double?
    var quantity:Int?

In order to save these struct or our cart info to USerDefaults, first we need to encode its as a JSON using JSONEncoder which will give us Data object. Finally, we will save this data object to USerDefaults. Please have a look at given below code snippet.

  let product = CartItem(ipn: "123", shortName: "Short", longName: "long", description: "", thumbnail: "", packaging: "", pricePerUnit: 23.0, quantity: 1)
  var itemArray = [CartItem]()
  let cart = Cart(items: itemArray)
  let encoder = JSONEncoder()
  if let encoded = try? encoder.encode(cart) {
       let defaults = UserDefaults.standard
       defaults.set(encoded, forKey: "cart")

Reading saved Struct data from USerDefaults

In order to read data back, we will use JSONDecoder to decode the save data to our Structs. Below is the code snippet, for reading struct data save to USerDefaults.

 let defaults = UserDefaults.standard
 if let savedCartData = defaults.object(forKey: "cart") as? Data {
     do {
           let decoder = JSONDecoder()
           let savedCart = try decoder.decode(Cart.self, from: savedCartData)
            print("Cart loaded with item =\(savedCart.items?.count ?? -1)"
        } catch let error {
                print("Error getting cart from defaults \(error)")