我無法理解和使用 catch 子句中的 DecodingError.typeMismatch 關聯值。
我可以在沒有相關值的情況下很好地使用它。我嘗試在我的 do 塊中解碼 Type A,然后捕獲 typeMismatch 并嘗試在 catch 塊中解碼 Type B。
如何使用關聯的值來嘗試捕獲第二個 typeMismatch,以便我可以嘗試在額外的 catch 塊中解碼 Type C?
例如,如果我捕獲 DecodingError.typeMismatch(let type, _),我可以在 where 子句中使用 type 來嘗試捕獲額外的 typeMismatch 錯誤嗎?
我一直在玩這個,回傳的關聯值“型別”是 Double 但這不是我嘗試解碼的。我真的不明白應該是什么型別。
編輯:添加我現有的代碼。我的前兩個案例運行良好,但是在添加第二個捕獲之后,Xcode 警告我它永遠不會被執行,因為我已經捕獲了那個錯誤。我想做的是使用 typeMismatch 和 where 子句的關聯值,這樣我就可以一次嘗試每個 catch 一個。
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)
}
}
}
uj5u.com熱心網友回復:
不幸的是你不能。您將需要嵌套捕獲。
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))
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516580.html
標籤:迅速错误处理枚举