evgenyneu/keychain-swift

Feature request - propertyWrapper support

gerchicov-bp opened this issue · 1 comments

https://www.avanderlee.com/swift/property-wrappers/
Here is an example for UserDefaults:

@propertyWrapper
struct UserDefault<T> {
    let key: String
    let defaultValue: T

    init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

Could you please make something similar for keychain?

@gerchicov-bp we've implemented something similar on our app using this, here's the implementation:

import KeychainSwift

@propertyWrapper struct KeychainBacked<Value> {
    let key: String
    let defaultValue: Value?

    let keychain: KeychainSwift = {
       let keychain = KeychainSwift(keyPrefix: "com.calm.calmapp")
       keychain.synchronizable = false
       return keychain
   }()

    init(key: String, defaultValue: Value? = nil) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: Value? {
        get {
            return (keychain.get(key) as? Value) ?? defaultValue
        }
        set {
            if let valueAsString = newValue as? String {
                keychain.set(valueAsString, forKey: key)
            } else {
                keychain.delete(key)
            }
        }
    }
}