Skip to content

Instantly share code, notes, and snippets.

@jeremy-w
Created November 12, 2020 13:08
Show Gist options
  • Save jeremy-w/e7537c36eb89ce3694df81b49cd90215 to your computer and use it in GitHub Desktop.
Save jeremy-w/e7537c36eb89ce3694df81b49cd90215 to your computer and use it in GitHub Desktop.
class Parent: Error {
var localizedDescription: String { "p" }
}
class Child: Parent {
override var localizedDescription: String { "c" }
}
print("Given two error classes, Parent, and Child a kind of Parent\n")
let e: Result<Int, Child> = .failure(Child())
let e2: Result<Int, Parent>
// e2 = e // <-- GIVES ERROR BELOW
print("You cannot directly assign a Result whose error type is Child to one whose error type is Parent:\n\n~~~ COMPILER SAYS ~~~\n", """
foo.swift:10:4: error: cannot assign value of type 'Result<Int, Child>' to type 'Result<Int, Parent>'
e2 = e
^
foo.swift:10:4: note: arguments to generic parameter 'Failure' ('Child' and 'Parent') are expected to be equal
e2 = e
^
~~~ :( ~~~
""")
print("But you can shim it by mapError({ $0 }), because a function can take a Child and return it as a Parent:\n")
// Succeeds with a simple shim.
e2 = e.mapError({ $0 })
print("- e =", String(reflecting: e), "\n- e2 =", String(reflecting: e2))
@jeremy-w
Copy link
Author

output when run through swift:

Given two error classes, Parent, and Child a kind of Parent

You cannot directly assign a Result whose error type is Child to one whose error type is Parent:

~~~ COMPILER SAYS ~~~
 foo.swift:10:4: error: cannot assign value of type 'Result<Int, Child>' to type 'Result<Int, Parent>'
e2 = e
   ^
foo.swift:10:4: note: arguments to generic parameter 'Failure' ('Child' and 'Parent') are expected to be equal
e2 = e
   ^
~~~ :( ~~~

But you can shim it by mapError({ $0 }), because a function can take a Child and return it as a Parent:

- e = Swift.Result<Swift.Int, shimming_result_error_covariance.Child>.failure(shimming_result_error_covariance.Child) 
- e2 = Swift.Result<Swift.Int, shimming_result_error_covariance.Parent>.failure(shimming_result_error_covariance.Child)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment