gpt4 book ai didi

ios - 如何创建一个包含符合协议(protocol)的对象的元组?

转载 作者:行者123 更新时间:2023-11-29 05:30:07 24 4
gpt4 key购买 nike

假设我想使用 JSON 资源测试一堆类型的序列化:

let bundle = Bundle(for: type(of: self))
let decoder = JSONDecoder()

let tests : [(filename: String, type: ???)] = [
("Employee", Employee.self),
("Job", Job.self)
]
for test in tests {
let filename = test.filename
let type = test.type

guard let url = bundle.url(forResource: filename, withExtension: "json") else {
XCTFail("Failed to load file: \(filename).json")
return
}
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: [])
let obj = try decoder.decode(type, from: data)
}
}

应该如何声明test元组?

最佳答案

我将使用通用函数来实现此目的,请参阅下面的示例:

//Model
struct Test: Decodable {
var name: String
var surname: String
var gender: String
}


//Generic function
func readJsonData<T: Decodable>(filename: String, completion: @escaping (T) -> ()) {

if let fileUrl = Bundle.main.url(forResource: filename, withExtension: "json") {
do {

let data = try Data(contentsOf: fileUrl)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(T.self, from: data)
completion(jsonData)

} catch {
print("error: \(error)")
}
}

return
}

//How to call the generic function
readJsonData(filename: "Test") { (obj: Test) in
//do something with your returned object of type Test
}

关于ios - 如何创建一个包含符合协议(protocol)的对象的元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57684991/

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