How can I store a Swift enum value in NSUserDefaults

前端 未结 7 746
猫巷女王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:02

    Swift 5.1 You can create property wrapper for this

    @propertyWrapper final class UserDefaultsLanguageValue {
        var defaultValue: LanguageType
        var key: UserDefaultsKey
    
        init(key: UserDefaultsKey, defaultValue: LanguageType) {
            self.key = key
            self.defaultValue = defaultValue
        }
    
        var wrappedValue: LanguageType {
            get { LanguageType(rawValue: UserDefaults.standard.object(forKey: key.rawValue) as? String ?? defaultValue.rawValue) ?? .en }
            set { UserDefaults.standard.set(newValue.rawValue, forKey: key.rawValue) }
        }
    }
    
    enum UserDefaultsKey: String {
        case language
    }
    
    enum LanguageType: String {
        case en
        case ar
    }
    

    And use it just like that

    @UserDefaultsLanguageValue(key: .language, defaultValue: LanguageType.en) var language
    

提交回复
热议问题