How can I store a Swift enum value in NSUserDefaults

前端 未结 7 740
猫巷女王i
猫巷女王i 2021-01-31 07:47

I have an enum like this:

enum Environment {
    case Production
    case Staging
    case Dev
}

And I\'d like to save an instance in NSUserDef

7条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 08:00

    Here is another alternative that can be be easily used with enums based on types (like String, Int etc) that can be stored by NSUserDefaults.

    @propertyWrapper
    struct StoredProperty {
        let key: String
        let defaultValue: T
    
        init(_ key: String, defaultValue: T) {
            self.key = key
            self.defaultValue = defaultValue
        }
    
        var wrappedValue: T {
            get {
                guard let rawValue = UserDefaults.standard.object(forKey: key) as? T.RawValue, let value = T(rawValue: rawValue) else {
                     return defaultValue
                }
                return value
            }
            set {
                UserDefaults.standard.set(newValue.rawValue, forKey: key)
            }
        }
    }
    

    Example usage:

    enum Environment: String {
        case Production
        case Staging
        case Dev
    }
    
    @StoredProperty("Environment", defaultValue: .Dev)
    var storedProperty: Environment
    

提交回复
热议问题