[英]How to save Enum to UserDefaults?
我正在尝试将枚举保存到UserDefaults
但无法成功执行此操作,因为在 do try catch 中出现错误。 我发现它与我的枚举有关,因为当我删除班级中的枚举时,它像以前一样正常工作。
class User: NSObject, NSCoding {
private(set) public var loginType: LoginType
// some other properties
init(name: String, username: String, email: String, profileImage: UIImage?) {
// some other inits
self.loginType = .email
}
init(name: String, username: String, telephoneNumber: String, profileImage: UIImage?) {
// some other inits
self.loginType = .telephoneNumber
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.loginType, forKey: LOGIN_TYPE_KEY)
}
required init?(coder aDecoder: NSCoder) {
self.loginType = aDecoder.decodeObject(forKey: LOGIN_TYPE_KEY) as! LoginType
}
}
这是我的枚举:
enum LoginType: String {
case email = "email"
case telephoneNumber = "telephoneNumber"
}
您必须保存枚举的rawValue
func encode(with aCoder: NSCoder) {
aCoder.encode(self.loginType.rawValue, forKey: LOGIN_TYPE_KEY)
}
required init?(coder aDecoder: NSCoder) {
let loginRaw = aDecoder.decodeObject(forKey: LOGIN_TYPE_KEY) as! String
self.loginType = LoginType(rawValue: loginRaw)!
}
考虑使用Codable
而不是NSCoding
。 您不需要NSObject
的子类,并且可以直接序列化 RawRepresentable 枚举。
如果原始值与案例匹配,则枚举可以声明得更短
enum LoginType: String {
case email, telephoneNumber
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.