Understanding Result Type in Swift 5
Swift 5 was released and made available with Xcode 10.2 which you can download from the Mac App store. Apart from the ABI stability, Swift 5 includes a lot of useful features including codable ranges, raw strings, future enums and my personal favorite result types.
Result type is an enum, which wraps the success and error callbacks. Consider a scenario where the user accesses a web API. The API can return the result asynchronously (success state) or it can return an error (failure state). The new Result type can wrap the result in separate enum cases, making it easier to access both states.
Implementation
Before invoking the web API we will implement our models. The API we will be using is available at “https://jsonplaceholder.typicode.com/posts”. It is just a dummy API which sends back dummy results. The implementation for our models is shown below:
The Post model is marked with Decodable, which will help us to decode the response and populate our model. The NetworkError enum represents different cases for errors which we might encounter when during our networking adventures. Now that we have our models implemented let’s check out the implementation of fetchPosts function which is responsible for retrieving all the posts from the web API.
As you can see we are using Result type in our completion closure. The Result type takes two types. The first one is the type returned in the case of success and the next one is the type returned in case of failure. Later we invoked the completion handler and invoke the .success or .failure based on our scenario.
Now we can start using our fetchPosts function.
Nice and simple!
If you want to learn more about the new features of Swift 5 programming language then check out my course “The Complete Guide to New Features in Swift 5”. Click on the link and the coupon will automatically be applied.
Thank you so much and happy coding!