Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Last active May 1, 2022 17:32
Show Gist options
  • Save andresr-dev/f9d7383d178c511deaab9282eaee3611 to your computer and use it in GitHub Desktop.
Save andresr-dev/f9d7383d178c511deaab9282eaee3611 to your computer and use it in GitHub Desktop.
This is an example of how to use UserDefaults inside a ViewModel. We should not store more than 500KB of data in UserDefaults
import Foundation
struct Card: Identifiable, Codable {
var id = UUID()
let prompt: String
let answer: String
}
@MainActor class ViewModel: ObservableObject {
@Published var cards = [Card]()
init() {
loadData()
}
func loadData() {
if let data = UserDefaults.standard.data(forKey: "Cards") {
if let decoded = try? JSONDecoder().decode([Card].self, from: data) {
cards = decoded
}
}
}
func saveData() {
if let data = try? JSONEncoder().encode(cards) {
UserDefaults.standard.set(data, forKey: "Cards")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment