Last active
December 12, 2022 19:28
-
-
Save stleamist/5433fe5ed17271c841b74bb0d4d3b9be to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Foundation | |
import KeychainAccess | |
@propertyWrapper | |
struct KeychainStorage<Value: Codable> { | |
let key: String | |
let service: String | |
let initialValue: Value | |
private let keychain: KeychainAccess.Keychain | |
private let encoder = JSONEncoder() | |
private let decoder = JSONDecoder() | |
init(wrappedValue initialValue: Value, _ key: String, service: String? = nil) { | |
self.initialValue = initialValue | |
self.key = key | |
self.service = service ?? Bundle.main.bundleIdentifier ?? "com.kishikawakatsumi.KeychainAccess" | |
self.keychain = KeychainAccess.Keychain(service: self.service) | |
} | |
var wrappedValue: Value { | |
get { | |
guard let data = try? keychain.getData(key), | |
let value = try? decoder.decode(Value.self, from: data) else { | |
return initialValue | |
} | |
return value | |
} | |
set { | |
guard let newData = try? encoder.encode(newValue) else { | |
return | |
} | |
try? keychain.set(newData, key: key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adapted to optional data: