小编gle*_*rik的帖子

使用JSONEncoder对符合协议的类型进行编码/解码

我正在尝试使用Swift 4中的新JSONDecoder/Encoder找到符合swift协议的编码/解码结构数组的最佳方法.

我举了一个例子来说明问题:

首先,我们有一个协议Tag和一些符合这个协议的类型.

protocol Tag: Codable {
    var type: String { get }
    var value: String { get }
}

struct AuthorTag: Tag {
    let type = "author"
    let value: String
}

struct GenreTag: Tag {
    let type = "genre"
    let value: String
}
Run Code Online (Sandbox Code Playgroud)

然后我们有一个Type文章,它有一个标签数组.

struct Article: Codable {
    let tags: [Tag]
    let title: String
}
Run Code Online (Sandbox Code Playgroud)

最后,我们对文章进行编码或解码

let article = Article(tags: [AuthorTag(value: "Author Tag Value"), GenreTag(value:"Genre Tag Value")], title: "Article Title")


let jsonEncoder = JSONEncoder()
let jsonData = try …
Run Code Online (Sandbox Code Playgroud)

encoding json swift swift4 codable

32
推荐指数
3
解决办法
2万
查看次数

标签 统计

codable ×1

encoding ×1

json ×1

swift ×1

swift4 ×1