Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save youn9k/1c9c1ab8891ac25eea58958745786051 to your computer and use it in GitHub Desktop.
Save youn9k/1c9c1ab8891ac25eea58958745786051 to your computer and use it in GitHub Desktop.
save array of struct to UserDefaults
import Foundation
struct Book: Codable {
let title: String
let author: String
}
let KeyForUserDefaults = "myKey"
func save(_ books: [Book]) {
let data = books.map { try? JSONEncoder().encode($0) }
UserDefaults.standard.set(data, forKey: KeyForUserDefaults)
}
func load() -> [Book] {
guard let encodedData = UserDefaults.standard.array(forKey: KeyForUserDefaults) as? [Data] else {
return []
}
return encodedData.map { try! JSONDecoder().decode(Book.self, from: $0) }
}
save([Book(title: "The Great Gatsby", author: "Fitzgerald"),
Book(title: "Ulysses", author: "Joyce")])
let books = load()
print(books) //[Book(title: "The Great Gatsby", author: "Fitzgerald"), Book(title: "Ulysses", author: "Joyce")]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment