gpt4 book ai didi

json - Swift 和 Codable : Encodable tree struct terminating in values that obey custom protocol

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:39 24 4
gpt4 key购买 nike

我正在尝试使树数据结构遵守可编码协议(protocol)。树终止于遵守协议(protocol)“终端”的“某个对象”。终端扩展了 Codable。

树的每个节点都是一对。它有一个键和一个值。该值是一对或终端。

主要有两个问题:

1)我希望这种结构编码为 JSON,这样

class Pair: Codable {
var key: String?
var value: Codable?
}

let outputSimple = Pair(key: "a test key", value: "a test value")
// encodes to
// {"a test key": "a test value"}
// whereas currently encodes to
// {}

let outputComplex = Pair(key: "a parent", value: Pair(key: "another pair", value: "a test value"))
// encodes to
// {"a parent": {"another pair", "a test value"}}

编辑:第 2 部分可能会稍微混淆问题。为了澄清上面的问题,如果我有

class Pair: Codable {
var key: String
var value: String
}
let p = Pair(key:"foo", value: "bar")

我怎样才能让它输出 {"foo":"bar"} 而不是 {key:foo, value:bar}?我试过了

    override func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
container.encode(contentsOf: [key: value])
}

但出现错误“实例方法‘encode(contentsOf:)’要求‘(key: _, value: _)’符合‘Encodable’”

2) 我正在尝试以下操作,但它似乎不起作用。我得到“对不符合协议(protocol)‘可解码’”

protocol TreeNode: Codable {} 
struct Pair: TreeNode {
var key: String?
var value: TreeNode?
}

extension String: TreeNode {}

我可以通过将 TreeNode 设为一个类并将 Pair 设为一个子类来解决这个问题。这也可能是正确的 Swift 行为。但是,我想知道是否有更多双眼可以解释这个问题。我假设只要我确保所有值都是类型对,或者是其他遵循 Codable 的东西,那么它就可以工作。

最佳答案

这行不通。

value 必须是符合 Codable 的具体类型,而不是协议(protocol)本身或符合 Codable

的第二个协议(protocol)

你可以做的是将value声明为generic

class Pair<T: Codable>: Codable {
var key: String?
var value: T?

init(key: String?, value: T?) {
self.key = key
self.value = value
}
}

它可以同时编码outputSimpleoutputComplex

关于json - Swift 和 Codable : Encodable tree struct terminating in values that obey custom protocol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55692056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com