我有一个类定义为:
struct MyObject: Identifiable{
var id = UUID()
var paramA: String
var paramB: String
var paramC: String
init(paramA: String, paramB: String = "default", paramC: String = "tomato" ){
self.paramA = paramA
self.paramB = paramB
self.paramC = paramC
}
}
用于使用landmarkData 读取Json Im
let landmarkData: [Landmark] = load("inputData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find (filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load (filename) from main bundle:n(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse (filename) as (T.self):n(error)")
}
}
我已经决定数据也可以通过Json,所以我改变了MyObject的结构(添加Hashable、Codable并更改Int的var id=UUID((,然后移动到参数(
struct MyObject: **Hashable, Codable**, Identifiable{
**var id = Int**
var paramA: String
var paramB: String
var paramC: String
init(**id : Int,** paramA: String, paramB: String = "default", paramC: String = "tomato" ){
**self.id = id**
self.paramA = paramA
self.paramB = paramB
self.paramC = paramC
}
}
这适用于具有每个对象上所有关键点的Json。但我不想定义将采用默认值的键(paramA和paramB键(。我不必在Json中定义id。
inputData.json
[{
"paramA": "Hello",
"paramB": "World",
"paramC": "!!!",
},
{
"paramA": "Hi",
},
{
"paramA": "Hello",
"paramC": "??",
}]
它通过添加解码器int和尝试来处理无法带来密钥的情况。我不知道是否有更好的解决方案。
struct MyObject: Identifiable{
var id = UUID()
var paramA: String
var paramB: String
var paramC: String
init(paramA: String, paramB: String = "default", paramC: String = "tomato" ){
self.paramA = paramA
self.paramB = paramB
self.paramC = paramC
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .paramA)
do {
paramB = try values.decode(String.self, forKey: .paramB)
}
catch {
paramB = "default"
}
do {
paramC = try values.decode(String.self, forKey: .paramC)
}
catch {
paramC = "default"
}
}