How can I store a Swift enum value in NSUserDefaults

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

    Using rawValue for the enum is one way of using types that can be stored in NSUserDefaults, define your enum to use a rawValue. Raw values can be strings, characters, or any of the integer or floating-point number types :

    enum Environment: String {
        case Production = "Prod"
        case Staging    = "Stg"
        case Dev        = "Dev"
    }
    

    You can also create an enum instance directly using the rawValue (which could come from NSUserDefaults) like:

    let env = Environment(rawValue: "Dev")
    

    You can extract the rawValue (String) from the enum object like this and then store it in NSUserDefaults if needed:

    if let myEnv = env {
        println(myEnv.rawValue)
    }
    
    
    func saveEnvironment(environment : Environment){
        NSUserDefaults.standardUserDefaults().setObject(environment.rawValue, forKey: kSavedEnvironmentDefaultsKey)
    }
    

提交回复
热议问题