【发布时间】:2019-12-18 23:16:01
【问题描述】:
我想弄清楚如何对 catch 中错误类型的 enum-with-associated-value 属性进行模式匹配。使用枚举 没有 关联值时,一切都按预期工作,但我似乎无法找出这种情况的正确模式。
struct MyError: Error {
enum Size {
case big, small
}
enum Solution {
case runAway
case other(String)
}
let size: Size
let solution: Solution
}
func action() {
do {
// ...
}
catch let error as MyError where error.size == .big {
// This works fine, as `size` has no associated values.
}
catch let error as MyError where error.solution == .other {
// I want to handle all cases of `Solution.other` here, regardless of the associated value.
}
catch {
// ...
}
}
第二个catch 模式将无法编译(正如预期的那样,由于枚举具有关联值)。我完成此操作的通常方法是if case .runAway = error.solution {...},但将其集成到catch 模式中是个问题。
我尝试了if case/let case/case let 的多种组合,但无法在单个catch 模式匹配语句中使用。鉴于模式匹配的强大功能和灵活性,这感觉应该是可能的,所以我希望我只是忽略了一些东西。
感谢您的帮助!
【问题讨论】:
标签: swift pattern-matching try-catch