这是我生成的一些 yaml :
byTeam:
- t0: { description: "Find a video of an object being selected and deselected", bestAnswer: [ 0 ]}
- t1: { description: "Reveal and hide numeric controls", bestAnswer: [ 1 ]}
- t2: { description: "Reveal and hide the tools", bestAnswer: [ 2 ]}
解析此错误时遇到的错误是:
no decode typeMismatch(Yams.Node.Mapping, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "assignments", intValue: nil), _YAMLCodingKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "challenges", intValue: nil), _YAMLCodingKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "byTeam", intValue: nil)], debugDescription: "Expected to decode Mapping but found Node instead.", underlyingError: nil))
这是新数据,进一步嵌套到已经工作的 yaml 文件中。它最终会被解析成这个结构:
struct CodableChallenge : Codable {
var title : String
var type : String
var description : String
var uuid : UUID
var videos : Array<String>
var bestAnswer : Array<Int>
var userAnswer : Array<Int>?
var byTeam : Dictionary<String, TeamChallenge>?
}
struct TeamChallenge : Codable {
var description : String
var bestAnswer : Array<Int>
}
产生错误的代码是
do {
let decoded = try decoder.decode(MenuScreenVC.CodableCurriculum.self, from: src)
manifestObsolete = curriculum == nil || decoded.referenceDate! > curriculum!.referenceDate!
self.newManifest = decoded
NotificationCenter.default.post(name: NSNotification.Name("gotManifest"), object: nil)
return
} catch {
print("no decode \(error)")
}
我对 yaml 并不完全陌生,我很多年前就在 RoR 中使用过它。但我认为我没有注意到的是更深层次的嵌套。该错误似乎表明它获取的数据看起来不像简单的映射,但为什么呢?
您以一种没有意义的方式混合数组和字典,并且与您的代码所期望的不匹配。
每个刻度线都会启动一个新对象。每个带有冒号后缀的标签都标记对象中的一个键。所以你写的已经生效了:
byTeam: [
{ t0: { ... } },
{ t1: { ... } },
{ t2: { ... } },
]
您只需删除这些
tN
值即可:
byTeam:
- { description: "Find a video of an object being selected and deselected", bestAnswer: [ 0 ]}
- { description: "Reveal and hide numeric controls", bestAnswer: [ 1 ]}
- { description: "Reveal and hide the tools", bestAnswer: [ 2 ]}