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?
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?
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