如何使用可分解协议为具有不同键的相同Json属性创建通用类

时间:2018-09-04 11:39:27

标签: ios json swift swift4 decodable

{
    "actions" : {
        "upvote" : {
            "delete" : true,
            "read" : true,
            "create" : true,
            "update": true
        },
        "read" : {
            "delete" : true,
            "update" : true,
            "read" : true,
            "create" : true
        }
    }
}

我有来自服务器的Json响应,下面是使用Decodable协议创建的模型结构

struct Actions: Decodable {
    let upvote: UpvoteStatus
    let read: ReadStatus

    enum CodingKeys: String, CodingKey {
        case upvote
        case read
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.upvote = try container.decode(UpvoteStatus.self, forKey: .upvote) {
        self.read = try container.decode(ReadStatus.self, forKey: .read)
    }
}

struct UpvoteStatus: Decodable {
    let delete: Bool
    let update: Bool
    let read: Bool
    let create: Bool
}

struct ReadStatus: Decodable {
    var delete: Bool
    var update: Bool
    var read: Bool
    var create: Bool
}

这很好用,但是会创建很多重复的代码,因为UpvoteStatus和ReadStatus结构具有相似的属性,并且来自服务器的JSON相似,只是键不同。

有什么办法可以创建一个通用的状态结构,将状态属性添加到R​​eadStatus和UpvoteStatus类

struct Status: Decodable {
    let delete: Bool
    let update: Bool
    let read: Bool
    let create: Bool
} 

现在,我要添加以下内容,以便删除重复的代码。

struct UpvoteStatus: Decodable {
    let status: Status
}

struct ReadStatus: Decodable {
    let status: Status
}

2 个答案:

答案 0 :(得分:2)

可能这是您所需要的,也许您在考虑中太努力了:

AASID

答案 1 :(得分:0)

无需编写自定义初始化程序并显式定义编码键。

您可以简单地写

struct Response: Codable {

    let actions: Actions

    struct Actions : Codable {
        let upvote: Element
        let read: Element

        struct Element: Codable {
            let delete: Bool
            let read: Bool
            let create: Bool
            let update: Bool
        }
    }
}