-2

I'm looking for an updated way to save an array of structs to UserDefaults using Swift 5.

Here's a question asked several years ago that works with Swift 4: Save Struct to UserDefaults

Is there an updated version/method for doing this for Swift 5?

Lemon
  • 1,184
  • 11
  • 33
  • 2
    Nope, that answer holds up – EmilioPelaez Oct 24 '20 at 00:11
  • @EmilioPelaez Thanks for the reply :) I'm probably just being stupid so I'll look at it again – Lemon Oct 24 '20 at 00:36
  • 2
    @Lemon I would just use `data(forKey:)` instead of `value(forKey:)`when loading it. The later is for KVO – Leo Dabus Oct 24 '20 at 01:08
  • @Lemon I just took a peek at those answers and those will get the job done. Just be very careful what you dump in UserDefaults. If you're putting anything sensitive in there, make sure you encrypt it using CryptoKit or something like that. Here's a post on that. https://medium.com/swlh/common-cryptographic-operations-in-swift-with-cryptokit-b30a4becc895 – Adrian Oct 24 '20 at 01:14
  • You can also just use JSON encoder/decoder and write it to disk. I wouldn't recommend using UserDefaults to persist your app data. It is meant for persisting your app settings (UI). Regarding security you can save it in a directory not accessible to the user. Is is iOS or macOS? – Leo Dabus Oct 24 '20 at 01:18
  • 1
    This + Codable is the 2020 solution. https://developer.apple.com/documentation/swiftui/appstorage/init(wrappedvalue:_:store:)-33hrf –  Oct 24 '20 at 04:28

1 Answers1

-2

Use The Codable protocol to save a struct in UserDefaults

For Example :

Here we define Student struct

struct Student: Codable {
    var name: String
}

Now encode it as JSON using JSONEncoder, which will send back a Data instance you can send straight to UserDefaults

let mark = Student(name: "Mark Luther")

let encoder = JSONEncoder()

if let encoded = try? encoder.encode(mark) {
    let defaults = UserDefaults.standard
    defaults.set(encoded, forKey: "SavedStudent")
}

Reading saved data back into a Student struct is a matter of converting from Data using a JSONDecoder, like this:

if let studentData = defaults.object(forKey: "SavedStudent") as? Data {
    let decoder = JSONDecoder()
    if let student = try? decoder.decode(Student.self, from: studentData) {
        print(student.name)
    }
}

Maybe this help you and another who want to find an answer for how to Save Struct to UserDefaults in Swift

Ashish
  • 706
  • 8
  • 22