0

I want to use UserDefaults, and I think I cant store an Instance of a Struct that I coded by myself, am I right? Now is my question; How can I store an Custom Struct Instance as Data. Thanks for your time Boothosh

1 Answers1

2

Define a custom object which conforms to Codable. A simple example:

struct MyObject: Codable {
    var something: String
}

And when you want to save it to UserDefaults, just encode it:

do {
    let encoded = try JSONEncoder().encode(MyObject(something: "String"))
    UserDefaults.standard.set(encoded, forKey: "kSavedObject")
} catch {
    print(error)
}

If you want to retrieve it, you can use decode:

if let data = UserDefaults.standard.data(forKey: "kSavedObject") {
    do {
        let myRetrievedObject = try JSONDecoder().decode(MyObject.self, from: data)
    } catch {
        print(error)
    }
}
πter
  • 1,899
  • 2
  • 9
  • 23