Skip to content

Instantly share code, notes, and snippets.

@d-date
Created September 10, 2018 09:29
Show Gist options
  • Save d-date/6170b4a7dfb2f78e472c6a03ac32827c to your computer and use it in GitHub Desktop.
Save d-date/6170b4a7dfb2f78e472c6a03ac32827c to your computer and use it in GitHub Desktop.
struct Hoge: Storagable {
let id: Int
let name: String
}
protocol Storagable: Codable {}
extension Storagable {
func save(key: String = "\(Self.self)", userDefaults: UserDefaults = .standard) throws {
let data = try JSONEncoder().encode(self)
userDefaults.setValue(data, forKey: key)
}
func load(key: String = "\(Self.self)", userDefaults: UserDefaults = .standard) throws -> Self? {
guard let data = userDefaults.data(forKey: key) else {
return nil
}
let json = try JSONDecoder().decode(Self.self, from: data)
return json
}
}
let hoge = Hoge(id: 1, name: "fuga")
try hoge.save()
let loadedData = try hoge.load() // Hoge(id: 1, name: fuga)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment