How to save an array of objects to NSUserDefault with swift?

Swift 4

We need to serialize our swift object to save it into userDefaults.

In swift 4 we can use Codable protocol, which makes our life easy on serialization and JSON parsing

Workflow(Save swift object in UserDefaults):

  1. Confirm Codable protocol to model class(class Place : Codable).
  2. Create object of class.
  3. Serialize that class using JsonEncoder class.
  4. Save serialized(Data) object to UserDefaults.

Workflow(Get swift object from UserDefaults):

  1. Get data from UserDefaults(Which will return Serialized(Data) object)
  2. Decode Data using JsonDecoder class

Swift 4 Code:

class Place: Codable {
    var latitude: Double
    var longitude: Double

    init(lat : Double, long: Double) {
        self.latitude = lat
        self.longitude = long
    }

    public static func savePlaces(){
        var placeArray = [Place]()
        let place1 = Place(lat: 10.0, long: 12.0)
        let place2 = Place(lat: 5.0, long: 6.7)
        let place3 = Place(lat: 4.3, long: 6.7)
        placeArray.append(place1)
        placeArray.append(place2)
        placeArray.append(place3)
        let placesData = try! JSONEncoder().encode(placeArray)
        UserDefaults.standard.set(placesData, forKey: "places")
    }

    public static func getPlaces() -> [Place]?{
        let placeData = UserDefaults.standard.data(forKey: "places")
        let placeArray = try! JSONDecoder().decode([Place].self, from: placeData!)
        return placeArray
    }
}

Leave a Comment