如何将枚举案例值保存到UserDefaults中以备将来使用 [英] How do I save an Enum Case value to UserDefaults for further usage

查看:77
本文介绍了如何将枚举案例值保存到UserDefaults中以备将来使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将枚举大小写的值保存到 UserDefaults ?我已经尝试过,没有运气.我检查了包括该站点在内的多个站点,但是没有运气,它们都位于Swift 2或我完全无法翻译的Objective-c中.

How do I save the value of an enum case to UserDefaults? I have tried and had no luck. I checked multiple sites including this one, but with no luck, they all are in Swift 2 or in Objective-c which I can't translate at all.

推荐答案

-UPDATE-

为自己弄清楚,我必须在枚举实例中添加一个整数扩展名,以便枚举具有要保存的值

figured It out for myself I had to add an integer extension to my enum case so the enum had a value to save

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

so I started with two global variables at the top of my file containing the switch method

var switchCurrentType = .default1
var currentDefaultType = UserDefaults().integer(forkey: "CurrentDefaultType")

然后,我在切换大小写的文件中声明了枚举大小写(例如,如果要打开按钮或在didMoveToView方法中将大小写放在这里)

then I declared the enum case in the file where I was switching the cases (like if you want to switch on the press of a button or in a didMoveToView method you put your case here)

enum ExampleEnum : Int {
    case default1
    case default2
}

然后我在切换外壳时会用到它

then I use this when switching the case

switchCurrentType = .default1 //or whatever you are trying to switch to

,我将其保存到UserDefaults

and I use this to save it to UserDefaults

UserDefaults.standard.set(switchCurrentType.rawValue, forKey: "CurrentDefaultType")

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

here is reading the saved data for further usage

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

这篇关于如何将枚举案例值保存到UserDefaults中以备将来使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆