[swift-evolution] [proposal] Either in the Swift Standard Library
Kevin Ballard
kevin at sb.org
Thu Jan 28 12:33:14 CST 2016
On Thu, Jan 28, 2016, at 10:13 AM, Chris Lattner wrote:
> FWIW, I’m in favor of typed throws, but only of a single type that conforms to ErrorType. “throws” would be sugar for “throws ErrorType”. The most common case I would imagine people using is “throws SomeEnum”. I’m personally not interested in supporting “throws A,B”.
That seems like a very sensible approach to take. We'd want to figure out some way to make it convenient to coerce some typed error into another typed error that "contains" the first, so that way I can say something like
enum FooError: ErrorType { ... }
enum BarError: ErrorType {
case Foo(FooError)
// ...
}
func foo() throws FooError {
// ...
}
func bar() throws BarError {
try foo()
}
and have the call to `try foo()` implicitly wrap the FooError in BarError.
Rust solved this by defining a trait std::convert::From that takes a type parameter and converts from that type parameter to Self (and every type T implicit implements From<T> so you can always convert from a type to itself). And its try!() macro passes all errors through convert::From::from(err), so if you have a "parent" error type that can contain a "child" error type, you just implement From<Child> on the Parent and now errors will get implicitly converted whenever the try!() macro is used. Of course, this relies on a few features that Swift doesn't have, and Swift's `try` is built into the language instead of being a standard library macro, but I can imagine that we might have some language support for similar behavior (heck, we could even make it so that any enum that conforms to ErrorType and has a variant with a single associated value that's another ErrorType will implicitly be able to convert from the child ErrorType to the parent ErrorType when calling a typed throwing method with try).
-Kevin Ballard
More information about the swift-evolution
mailing list