Created
September 10, 2018 09:29
-
-
Save d-date/6170b4a7dfb2f78e472c6a03ac32827c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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