SE-0235 - Add Result to the Standard Library

Although the review period is over, please let me leave my comment. I have been thinking about it for days.

If I correctly understood what you intended in the comment below you linked,

it seems to suggest that JSONDecoder.decode(_:from:) returns Results instead of throwing errors.

I think usefulness of automatic propagation (throws) is not limited to "systemic errors". For example, if we have an API to decode JSONs manually, and if manual propagation (Result) is preferred for non "systemic errors", the API would return Results like JSONDecoder.decode(_:from:). Then decoding JSONs manually would be written like below with complex conversions.

func decodeFoo(from json: JSON) -> Result<Foo, DecodingError> {
    return Result {
        let a: Int = try json["a"].unwrapped()
        let b: Bool = try json["b"].unwrapped()
        let c: String = try json["c"].unwrapped()
        return Foo(a: a, b: b, c: c)
    }.mapError { $0 as! DecodingError }
}

If the API throws errors directly, it can be written much more simply as follows (assuming that throwing subscripts referred in SE-0148 are available).

func decodeFoo(from json: JSON) throws -> Foo {
    let a: Int = try json["a"]
    let b: Bool = try json["b"]
    let c: String = try json["c"]
    return Foo(a: a, b: b, c: c)
}

As seen in the example above, I think automatic propagation is also useful for non "systemic errors". So I prefer using Result more limitedly as @John_McCall commented.

Then I think it is better not to add Result to the standard library now. If Result is added to the standard library now, I am sure that it will be widely abused instead of throws. I guess 90% of actual use cases of Result today are for asynchronous operations and typed errors. Because async/await and typed throws are not supported currently, Result will be the only way for the cases. If async/await and typed throws are introduced first (though I am not sure if typed throws should be supported), before Result, async/await and typed throws would be used in the cases. And the community could get experienced with them. Then Result could be used properly only when manual propagation is required.

6 Likes