Typed throws

Let me show an option though I am not sure if it is good.

Currently, it is discussed that the following two are equivalent.

func foo() throws
func foo() throws Error

In the context of "Improving the UI of generics", it can be written as shown below.

func foo() throws any Error

Instead of it, I think plain throws can be interpreted as throws some Error.

func foo() throws some Error

throws some Error has an advantage of performance because it does not require existential containers when it is specialized.

A problem of throws some Error is cases of throwing multiple types of errors in one function.

// `throws` stands for `throws some Error`
func foo() throws {
    if Bool.random() {
        throw AError()
    } else {
        throw BError()
    }
}

On the analogy of opaque result types, it seems like to cause a compilation error. However, because Error has self-conformance, any Errors can be throws as some Errors. Thus the code above can be interpreted as the following one.

func foo() throws some Error {
    if Bool.random() {
        throw AError() as any Error
    } else {
        throw BError() as any Error
    }
}

Then it could be possible to introduce throws as throws some Error without any source-breaking changes.

3 Likes