Avatar
enum FooError: Error { case bar case baz(Int) } func foo(_ x: Int) throws(FooError) -> Int { if Bool.random() { throw .bar } return x * x } //func foo() throws -> Int { // 42 //} extension Array { // func myMap<T>(_ transform: (Element) throws -> T) rethrows -> [T] { // var result: [T] = [] // for element in self { // result.append(try transform(element)) // } // return result // } func myMap<T, E: Error>(_ transform: (Element) throws(E) -> T) throws(E) -> [T] { var result: [T] = [] for element in self { result.append(try transform(element)) } return result } } let array = [2, 3, 5] print(array.myMap { $0 * $0 }) do { print(try array.myMap { try foo($0) }) } catch { print(error) } func main() { // do throws(FooError) { // print(try foo()) // _ = try foo() // } catch { // switch error { // case .bar: // print("bar") // case .baz(let x): // print("baz: \(x)") // } // } } let result: Result<Int, FooError> = .failure(.bar) do { try result.get() } catch { print(error) }
2:15 PM
enum FooError: Error { case bar case baz(Int) } func foo(_ x: Int) async throws(FooError) -> Int { if Bool.random() { throw .bar } return x * x } Task { async let x = foo(3) do { print(try await x) } catch { print(error) } }