Answers for "save struct array to UserDefaults swift"

1

save struct array to UserDefaults swift

struct Song:Codable {
    var title: String
    var artist: String
}

var songs: [Song] = [
    Song(title: "Title 1", artist: "Artist 1"),
    Song(title: "Title 2", artist: "Artist 2"),
    Song(title: "Title 3", artist: "Artist 3"),
]

UserDefaults.standard.set(try? PropertyListEncoder().encode(songs), forKey:"songs")

// here's how to get it back out again later:

if let data = UserDefaults.standard.value(forKey:"songs") as? Data {
    let songs2 = try? PropertyListDecoder().decode(Array<Song>.self, from: data)
}
Posted by: Guest on March-15-2020

Code answers related to "save struct array to UserDefaults swift"

Code answers related to "TypeScript"

Browse Popular Code Answers by Language