gpt4 book ai didi

swift - 如何在 Swift 4 中使用 JSONEncoder 对字典进行编码

转载 作者:搜寻专家 更新时间:2023-10-31 23:07:41 25 4
gpt4 key购买 nike

我想用 JSONEncoder 将字典编码为 json。它看起来像一个请求,接收一个字典作为参数并将其编码为 json 作为 http 主体。代码如下所示:

let dict = ["name": "abcde"]

protocol Request {
var params: [String: Encodable] { get set }
func encode<T>(_ value: T) throws -> Data where T : Encodable
}

extension Request {
func encode<T>(_ value: T) throws -> Data where T : Encodable {
return try JSONEncoder().encode(value)
}

var body: Data? {
if let encoded = try? self.encode(self.params) {
return encoded
}
return nil
}
}

struct BaseRequest: Request {
var params: [String : Encodable]
}

let req = BaseRequest(params: dict)
let body = req.body

但是这段代码出现错误

Fatal error: Dictionary<String, Encodable> does not conform to Encodable because Encodable does not conform to itself. You must use a concrete type to encode or decode.

我怎样才能使它可编码?

最佳答案

你必须按如下方式引入类型删除:

struct AnyEncodable: Encodable {

let value: Encodable
init(value: Encodable) {
self.value = value
}

func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}

}

struct Model: Encodable {

var params: [String: AnyEncodable]

}

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let json = try! encoder.encode(
Model(
params: [
"hello" : AnyEncodable.init(value: "world")
]
).params
)
print(String(data: json, encoding: .utf8))

关于swift - 如何在 Swift 4 中使用 JSONEncoder 对字典进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48544098/

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