I’m having trouble understanding and using the DecodingError.typeMismatch associated values in a catch clause.
I can use it fine without the associated values. I try decoding Type A in my do block and then catch the typeMismatch and try decoding Type B in the catch block.
How can I use the associated values to try catching a second typeMismatch, so that I can try decoding Type C in an additional catch block?
For example, if I catch DecodingError.typeMismatch(let type, _), can I use type in a where clause to try catching an additional typeMismatch error?
I’ve been playing around with this and the associated value ‘type’ that is returned is Double but that’s not what I’ve tried decoding. I don’t really understand what type is supposed to be.
Edit: Adding my existing code. My first two cases work perfectly, but after adding the second catch, Xcode warns me it won't ever be executed since I'm already catching that error. What I'd like to do is use the associated values of typeMismatch and a where clause, so that I can try each catch one at a time.
enum FeatureGeometryCoordinates: Decodable {
// cases
case polygon([[CGPoint]])
case multipolygon([[[CGPoint]]])
case point(CGPoint)
// init()
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
let polygonVal = try container.decode([[CGPoint]].self)
self = .polygon(polygonVal)
} catch DecodingError.typeMismatch {
let multipolygonVal = try container.decode([[[CGPoint]]].self)
self = .multipolygon(multipolygonVal)
} catch DecodingError.typeMismatch {
let pointVal = try container.decode(CGPoint.self)
self = .point(pointVal)
}
}
}
CodePudding user response:
Unfortunately you can't. You will need to nest the catch.
enum FeatureGeometryCoordinates: Decodable {
case polygon([[CGPoint]])
case multipolygon([[[CGPoint]]])
case point(CGPoint)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = try .polygon(container.decode([[CGPoint]].self))
} catch DecodingError.typeMismatch {
do {
self = try .multipolygon(container.decode([[[CGPoint]]].self))
} catch DecodingError.typeMismatch {
self = try .point(container.decode(CGPoint.self))
}
}
}
}