Re:The power of Result types in Swift
by jordansmithnz on Sunday June 17, 2018 @11:20PM
(#17335810)
The reason I started using this pattern is one I didn’t see the article mention:
With legacy style result callbacks, you’ll have both an optional value and an optional error returned - this corresponds to four possible states. If I’m using an API returning this, I have to think about two cases which probably won’t happen (neither an error or value, or both an error and a value). I’d like to think the API I’m using wouldn’t return those states, but since it’s not typed as such then code I’m writing should probably handle those cases gracefully.
By using a result type as per the article, it is well defined that only two states are possible. This pattern is a really nice one, and is a great use of Swift’s associated value enums.
Re:The power of Result types in Swift
by zoul on Monday June 18, 2018 @01:09AM
(#17336124)
To nitpick, the “both error and data” can happen, for example when the connection drops in the middle of a large response. Probably doesn’t change anything, but it’s good to know, maybe so that you don’t trap on an unexpected combination.
With legacy style result callbacks, you’ll have both an optional value and an optional error returned - this corresponds to four possible states. If I’m using an API returning this, I have to think about two cases which probably won’t happen (neither an error or value, or both an error and a value). I’d like to think the API I’m using wouldn’t return those states, but since it’s not typed as such then code I’m writing should probably handle those cases gracefully.
By using a result type as per the article, it is well defined that only two states are possible. This pattern is a really nice one, and is a great use of Swift’s associated value enums.