Avatar
enum FooError: Error { case bar case baz(Int) } func foo() throws(FooError) -> Int { if Bool.random() { return 42 } else { throw .bar } } func main() { do { print(try foo()) } catch { switch error { case .bar: print("bar") case .baz(let x): print("baz: \(x)") } } } func main() { do { print(try foo()) } catch .bar { print("bar)") } catch .baz(let x) { print("baz: \(x)") } catch { preconditionFailure("Never reaches here.") } } main()
1:50 PM
// 複数のエラー型をthrowするとき enum FooError: Error { case bar case baz(Int) } enum BarError: Error {} func foo() throws(FooError) -> Int { if Bool.random() { return 42 } else { throw .bar } } func bar() throws(BarError) { } func main() { do { print(try foo()) try bar() } catch let error as FooError { print("foo: \(error)") } catch let error as BarError { print("bar: \(error)") } catch { preconditionFailure("Never reaches here.") } }
1:53 PM
enum FooError: Error { case bar case baz(Int) } enum BarError: Error {} func foo() throws(FooError) -> Int { if Bool.random() { return 42 } else { throw .bar } } func bar() throws(BarError) { } func main() { do throws(FooError) { print(try foo()) _ = try foo() } catch { switch error { case .bar: print("bar") case .baz(let x): print("baz: \(x)") } } }