gpt4 book ai didi

swift 4 : With Codable `Generic parameter ' T' could not be inferred`

转载 作者:IT王子 更新时间:2023-10-29 05:25:07 25 4
gpt4 key购买 nike

我收到以下错误:

无法推断通用参数“T”

线上:let data = try encoder.encode(obj)

这是代码

import Foundation

struct User: Codable {
var firstName: String
var lastName: String
}

let u1 = User(firstName: "Ann", lastName: "A")
let u2 = User(firstName: "Ben", lastName: "B")
let u3 = User(firstName: "Charlie", lastName: "C")
let u4 = User(firstName: "David", lastName: "D")

let a = [u1, u2, u3, u4]

var ret = [[String: Any]]()
for i in 0..<a.count {
let param = [
"a" : a[i],
"b" : 45
] as [String : Any]
ret.append(param)
}


let obj = ["obj": ret]

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(obj) // This line produces an error
print(String(data: data, encoding: .utf8)!)

我做错了什么?

最佳答案

该消息具有误导性,真正的错误是 obj[String: Any] 类型,不符合 Codable因为 Any 没有。

仔细想想,Any 永远不可能符合Codable。当 JSON 实体可以是整数、字符串或对象时,Swift 将使用什么来存储它?您应该定义一个适当的结构来保存您的数据。

关于 swift 4 : With Codable `Generic parameter ' T' could not be inferred`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459734/

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