Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 5 Result type

Tags:

swift

swift5

In Swift 5 Apple introduced Result type. It's generic enum with two cases:

public enum Result<Success, Failure: Error> {
    case success(Success), failure(Failure)
}

Personally I used to two separate completions in network calls success: Completion and failure: Completion, but from what I see now, Apple pushing us to use single completion with Result type and then inside perform switch. So what are advantages of this approach with Result? Because in a lot of cases I can just omit error handling and don't write this switch. Thanks.

like image 743
Bohdan Savych Avatar asked Nov 02 '25 21:11

Bohdan Savych


1 Answers

You shouldn’t omit cases when Result is failure. You shouldn’t do it with Result and you shouldn’t do it with your closure for failure. You should handle errors.

Anyway, Result type was introduced for simplifing completion handlers. You can have single closure for handling success or failure (primary-opinion based if two separate closures are better or not). Also Result is designed for error handling. You can simply create your own enum conforming to Error and then you can create your own error cases.

like image 103
Robert Dresler Avatar answered Nov 05 '25 15:11

Robert Dresler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!