How can I store a Swift enum value in NSUserDefaults

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

    I am using like this type staging. Can you please try this it will help you.

    enum Environment: String {
      case Production  = "Production URL"
      case Testing     = "Testing URl"
      case Development = "Development URL"
    }
    //your button actions
     // MARK: set Development api
      @IBAction func didTapDevelopmentAction(_ sender: Any) {
        let env = Environment.Development.rawValue
        print(env)
        UserDefaults.standard.set(env, forKey:Key.UserDefaults.stagingURL)
      }
    // MARK: set Production api
      @IBAction func didTapProductionAction(_ sender: Any) {
        let env = Environment.Production.rawValue
        print(env)
        UserDefaults.standard.set(env, forKey:Key.UserDefaults.stagingURL)
      }
    
      // MARK: set Testing api
      @IBAction func didTapTestingAction(_ sender: Any) {
        let env = Environment.Testing.rawValue
        print(env)
        UserDefaults.standard.set(env, forKey:Key.UserDefaults.stagingURL)
      }
    //Based on selection act
    print("\(UserDefaults.standard.object(forKey: "stagingURL") ?? "")")
    

提交回复
热议问题