The values in UserDefaults
must be property lists, so you need to convert each tuple to a property list. A Data
is a property list, and there are several ways to convert things to Data
.
One way is to stop using a tuple and use a struct
instead. If all of the struct
's stored properties conform to Codable
, then you can ask Swift to generate everything needed to make the struct
itself conform to Codable
just by declaring the conformance. Both String
and Data
conform to Codable
.
Once the struct
is Codable
, you can convert one of them, or even an array of them, into a property list via JSONEncoder
or PropertyListEncoder
:
import Foundation
struct Bookie: Codable {
var name: String
var nameId: String
var bookId: String
var picture: Data
}
let bookies = [
Bookie(name: "mbro12", nameId: "id1", bookId: "b1", picture: Data()),
Bookie(name: "mayoff", nameId: "id2", bookId: "b2", picture: Data())
]
let bookiesData = try! PropertyListEncoder().encode(bookies)
UserDefaults.standard.set(bookiesData, forKey: "bookies")
let fetchedData = UserDefaults.standard.data(forKey: "bookies")!
let fetchedBookies = try! PropertyListDecoder().decode([Bookie].self, from: fetchedData)
print(fetchedBookies)