Created
November 5, 2020 03:26
-
-
Save yoxisem544/a71a536e8848b4856b44cc3f704ecff8 to your computer and use it in GitHub Desktop.
Property wrapper of keychain store
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
import Foundation | |
import KeychainAccess | |
//https://www.swiftbysundell.com/articles/property-wrappers-in-swift/ | |
public protocol AnyOptional { | |
var isNil: Bool { get } | |
} | |
extension Optional: AnyOptional { | |
public var isNil: Bool { self == nil } | |
} | |
@propertyWrapper | |
public struct KeychainStorage<T> where T: KeychainStorgaeDataAcceptable { | |
let key: String | |
let defaultValue: T | |
let keychain: Keychain | |
init(_ key: String, keychain: Keychain, defaultValue: T) { | |
self.key = key | |
self.defaultValue = defaultValue | |
self.keychain = keychain | |
} | |
public var wrappedValue: T { | |
get { | |
if let value = keychain[key] as? T { | |
return value | |
} else { | |
return defaultValue | |
} | |
} | |
set { | |
if let value = newValue as? AnyOptional, value.isNil { | |
keychain[key] = nil | |
} else { | |
if let value = newValue as? Data { | |
keychain[data: key] = value | |
} else if let value = newValue as? String { | |
keychain[string: key] = value | |
} else { | |
assertionFailure("Keychain should never store data other then String or Data type") | |
} | |
} | |
} | |
} | |
} | |
// see more: https://swiftbysundell.com/articles/property-wrappers-in-swift/ | |
extension KeychainStorage where T: ExpressibleByNilLiteral { | |
init(_ key: String, keychain: Keychain) { | |
self.key = key | |
self.defaultValue = nil | |
self.keychain = keychain | |
} | |
} | |
public protocol KeychainStorgaeDataAcceptable {} | |
extension String: KeychainStorgaeDataAcceptable {} | |
extension Data: KeychainStorgaeDataAcceptable {} | |
extension Optional: KeychainStorgaeDataAcceptable where Wrapped: KeychainStorgaeDataAcceptable {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment