首页 > 解决方案 > 我可以在 Codable 中使用枚举吗?

问题描述

我创建了一个枚举

enum FeedItemType: String {
    case selling = "SELLING"
    case news = "USER_NEWS"
}

该字符串与type我的 JSON 响应中返回的属性匹配。

在使用我正在创建的结构时,我希望能够在我的代码中的其他地方使用枚举值。这可能吗?

我正在尝试这样的事情

struct FeedItem: Codable, Equatable {
    var type: FeedItemType

    private enum CodingKeys: String, CodingKey {
        case type
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.type = try container.decode(FeedItemType.self, forKey: .type)
    }
}

但是我遇到了很多错误

没有“解码”候选产生预期的上下文结果类型“FeedItemType”

类型“FeedItem”不符合协议“Encodable”

标签: iosswiftcodable

解决方案


推荐阅读