How can I store a Swift enum value in NSUserDefaults

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

    If you would like to save/read data from UserDefaults and separate some logic, you can do it in following way (Swift 3):

    enum Environment: String {
        case Production
        case Staging
        case Dev
    }
    
    class UserDefaultsManager {
    
        static let shared = UserDefaultsManager()
    
        var environment: Environment? {
           get {
               guard let environment = UserDefaults.standard.value(forKey: kSavedEnvironmentDefaultsKey) as? String else {
                   return nil
               }
               return Environment(rawValue: environment)
           }
           set(environment) {
               UserDefaults.standard.set(environment?.rawValue, forKey: kSavedEnvironmentDefaultsKey)
           }
        }
    }
    

    So saving data in UserDefaults will look this way:

    UserDefaultsManager.shared.environment = Environment.Production
    

    And reading data, saved in UserDefaults in this way:

    if let environment = UserDefaultsManager.shared.environment {
        //you can do some magic with this variable
    } else {
        print("environment data not saved in UserDefaults")
    }
    
    0 讨论(0)
提交回复
热议问题