如何对其他枚举作为关联值的枚举使用可编码协议(嵌套枚举) [英] How to use Codable protocol for an enum with other enum as associated value (nested enum)

查看:230
本文介绍了如何对其他枚举作为关联值的枚举使用可编码协议(嵌套枚举)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天问了问题有关如何保存的问题 UserDefaults 内的嵌套枚举。

为此,我尝试使用 Codable 协议,但不确定我是否做对了。

I asked a question yesterday on how to save a nested enum inside UserDefaults.
I am trying to use the Codable protocol for this, but not sure if I am doing it correctly.

这里又是我要存储的枚举-> UserState

Here is again the enum I want to store -> UserState:

enum UserState {
    case LoggedIn(LoggedInState)
    case LoggedOut(LoggedOutState)
}

enum LoggedInState: String {
    case playing
    case paused
    case stopped
}

enum LoggedOutState: String {
    case Unregistered
    case Registered
}

以下是我到目前为止所做的步骤:

Here are the steps I did so far:

符合可编码协议并指定我们用于编码/解码的密钥:

Conform to Codable protocol and specify which are the keys we use for encode/decode:

extension UserState: Codable {
    enum CodingKeys: String, CodingKey {
        case loggedIn
        case loggedOut
    }

    enum CodingError: Error {
        case decoding(String)       
    }
}

添加了用于解码的初始化程序:

Added initializer for decode:

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    if let loggedIn = try? values.decode(String.self, forKey: .loggedIn) {
        self = .LoggedIn(LoggedInState(rawValue: loggedIn)!)
    }

    if let loggedOut = try? values.decode(String.self, forKey: .loggedOut) {
        self = .LoggedOut(LoggedOutState(rawValue: loggedOut)!)
    }

    throw CodingError.decoding("Decoding failed")
}

添加了编码方法:

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)

    switch self {
    case let .LoggedIn(value):
        try container.encode(value, forKey: .loggedIn) // --> Ambiguous reference to member 'encode(_:forKey:)'
    case let .LoggedOut(value):
        try container.encode(value, forKey: .loggedOut) // --> Ambiguous reference to member 'encode(_:forKey:)'
    }
}

编码方法给了我以上两个错误。现在不知道我在做什么错或者我在正确的轨道上。

The encode method gives me the above two errors. Not sure right now what I am doing wrong or if I am on the right track.

任何想法我做错了什么以及导致这两个模棱两可的错误的原因是什么?

Any idea what I am doing wrong and what causes these two ambiguous errors ?

推荐答案

关联的 LoggedInState LoggedOutState ,但您必须对其 rawValue (字符串)进行编码:

The associated value is LoggedInState or LoggedOutState but you have to encode its rawValue (String):

    case let .LoggedIn(value):
        try container.encode(value.rawValue, forKey: .loggedIn)
    case let .LoggedOut(value):
        try container.encode(value.rawValue, forKey: .loggedOut)
    }

根据解码方法,可从 rawValue 创建枚举案例。

according to the decode method where you're creating the enum cases from the rawValue.

这篇关于如何对其他枚举作为关联值的枚举使用可编码协议(嵌套枚举)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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