如何将Enum Case值保存到UserDefaults以供进一步使用

Ano*_*ous 3 enums swift

如何保存枚举案例的值UserDefaults?我试过,没有运气.我检查了多个网站,包括这个,但没有运气,他们都在Swift 2或Objective-c,我根本无法翻译.

vad*_*ian 12

例如,使用符合属性列表的原始值创建枚举 Int

enum ExampleEnum : Int {
    case default1
    case default2
    case default3   
}
Run Code Online (Sandbox Code Playgroud)

隐含地,第一种情况是0,第二种情况是1,依此类推.

现在您可以保存(原始)值 UserDefaults

UserDefaults.standard.set(currentDefaultType.rawValue, forKey:"Foo")
Run Code Online (Sandbox Code Playgroud)

读回来

currentDefaultType = ExampleEnum(rawValue: UserDefaults.standard.integer(forKey:"Foo"))!
Run Code Online (Sandbox Code Playgroud)


Ano*_*ous 2

-更新-

我自己想通了,我必须向我的枚举案例添加一个整数扩展,以便枚举有一个要保存的值

所以我从文件顶部的两个全局变量开始,其中包含 switch 方法

var switchCurrentType = .default1
var currentDefaultType = UserDefaults().integer(forkey: "CurrentDefaultType")
Run Code Online (Sandbox Code Playgroud)

然后我在切换案例的文件中声明了枚举案例(例如,如果您想按下按钮或在 didMoveToView 方法中切换案例,则将案例放在这里)

enum ExampleEnum : Int {
    case default1
    case default2
}
Run Code Online (Sandbox Code Playgroud)

然后我在切换案例时使用它

switchCurrentType = .default1 //or whatever you are trying to switch to
Run Code Online (Sandbox Code Playgroud)

我用它来将其保存到 UserDefaults

UserDefaults.standard.set(switchCurrentType.rawValue, forKey: "CurrentDefaultType")
Run Code Online (Sandbox Code Playgroud)

这里正在读取保存的数据以供进一步使用

//in the didMoveToView method put this code in
switchCurrentType = ExampleEnum(rawValue: UserDefaults.standard.integer(forKey: "CurrentDefaultType"))! //make sure exclamation mark at the end is there or it won't read properly
Run Code Online (Sandbox Code Playgroud)