Swift 如何将枚举大小写值保存到UserDefaults以供进一步使用

Swift 如何将枚举大小写值保存到UserDefaults以供进一步使用,swift,enums,Swift,Enums,如何将枚举大小写的值保存到UserDefaults?我试过了,但运气不好。我检查了包括这一个在内的多个站点,但运气不佳,它们都在Swift 2或Objective-c中,我根本无法翻译它们。使用符合属性列表的原始值创建枚举,例如Int enum ExampleEnum : Int { case default1 case default2 case default3 } 隐式地,第一种情况是0,第二种情况是1,依此类推 现在您可以将(原始)值保存在UserDefa

如何将枚举大小写的值保存到
UserDefaults
?我试过了,但运气不好。我检查了包括这一个在内的多个站点,但运气不佳,它们都在Swift 2或Objective-c中,我根本无法翻译它们。

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

enum ExampleEnum : Int {
    case default1
    case default2
    case default3   
}
隐式地,第一种情况是0,第二种情况是1,依此类推

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

UserDefaults.standard.set(currentDefaultType.rawValue, forKey:"Foo")
然后再读一遍

currentDefaultType = ExampleEnum(rawValue: UserDefaults.standard.integer(forKey:"Foo"))!

-更新-

我自己弄明白了,我必须给我的枚举案例添加一个整数扩展名,这样枚举就有了一个要保存的值

因此,我从包含switch方法的文件顶部的两个全局变量开始

var switchCurrentType = .default1
var currentDefaultType = UserDefaults().integer(forkey: "CurrentDefaultType")
然后,我在切换案例的文件中声明了enum案例(例如,如果您想按下按钮或在didMoveToView方法中切换,请将案例放在这里)

然后我在切换案例时使用这个

switchCurrentType = .default1 //or whatever you are trying to switch to
我用这个来保存到UserDefaults

UserDefaults.standard.set(switchCurrentType.rawValue, forKey: "CurrentDefaultType")
下面是读取保存的数据以供进一步使用

//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

这更像是你有一个带有3个值的
ExampleEnum
,然后你需要以某种方式将所选值保留为默认值。似乎你已经在问题的地方写了一个答案。你通常不会因为这种错误的用法而得票。提高问题本身的意义,并写一个答案作为答案。我建议你快点,因为这个网站的错误使用经常被否决。我实现了它,但它给我一个错误,说我的案例在ExampleEnum中找不到,我引用“Enum案例'default1'在类型'ExampleEnum'中找不到”请编辑你的问题并添加受影响的代码。我的解决方案应该是有效的。这是我改变currentDefaultType的方式。首先,我在我的viewController顶部声明“var currentDefaultType=ExampleEnum(rawValue:UserDefaults.standard.integer(forKey:“Foo”)”),然后我像这样切换“currentDefaultType=.default1”。问题中的代码无论如何都不会编译。您必须告诉编译器类型是
var currentDefaultType:ExampleEnum=.default1
还是不带注释
var currentDefaultType=ExampleEnum.default1
让我试试保持-编辑-我更改了上面的代码以包含一个似乎正在工作的自定义函数
//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