Typed Errors in Swift with the Result Type
The
Result
type has been around for a while, there have been many variations on it on community maintained frameworks such as Alamofire, and RxSwift, there’s even a μframework called Result before Swift 5 introduced the Result type on SE-0235.
Gracefully handling scenarios with two outcomes is something we as developers would usually work on. The Result
type has been added for handling these two outcomes, a Success or a Failure.
This is where the Result
type comes in.
Use
Result
whenever an operation has the possibility of failure. ~ Rob Rix
The Result
type is basically just an enum that contains two cases
Before coding for a scenario like this would normally require you to use a do try catch
block, but sometimes a concrete Error
data type will be more advantageous, and what is Swift if not for its powerful type system.
Take an email TextField for example, normally we do have the following checks before we store the data.
- Is the string is empty?
- Does the string have white spaces?
- Is the string a valid email address?
First, let’s create an Error
type which contains the rules above.
Then let’s create a method that will have to validate the TextFields’s text.
Using this would be as simple as using a switch
statement
You can also implement this using a do try catch
statement. To do that you can use the .get()
method of Swift’s Result
which returns the Success
value or throws an Error
if the Result
evaluates into a Failure
.
Long story short with Result
, errors are typed, concise, and you don’t need to have a catch-all block like the do try catch
statement but the beauty of this is if ever you want to use thedo try catch
the .get()
method is already available for use.
If you’re reading this, then you’ve reached the end. Cheers! 🍻
If you have any comments, suggestions, questions, or ideas for new blog posts leave a comment down below. 👇👇
Thank you for taking the time on reading my article. 🎉
Gif from Tenor