Native Shopify Mobile App with 20 new features
Kickstart your hyperlocal marketplace in Corona pandemic with a starter guide
Android App Development
iOS App Development
Cross Platform App Development
Hire on-demand project developers and turn your idea into working reality.
Big thanks to Webkul and his team for helping get Opencart 184.108.40.206 release ready!
Owner and Founder. Opencart
Swift 5 introduces a new Result type to handle the result of an asynchronous function using an enum.
A value that represents either a success or a failure, including an associated value in each case.
Before Result type below is the ways in which we create Asynchronous functions:
The problem is that handling the result of the above function becomes quite tricky. Even if the error argument is nil, there’s no compile-time guarantee that the data we’re looking for is actually there — it might be nil as well for all we know, which would put our code in a bit of a strange state.
They contain only 2 cases that both uses Swift Generic with associated value:
1. Success with the value of the result.
2. Failure with the type that implements Error protocol.
The API which we are using for this is “https://jsonplaceholder.typicode.com/posts”. It is just a dummy API which sends back dummy results. The modal we have created for this demonstration is given 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 part of Swift 5, the standard library is also getting its very own implementation of Result. One advantage of Result being included in the standard library is that individual frameworks and apps no longer have to define their own — and more importantly, no longer have to convert between different flavors of the same kind of type.
Swift 5 also brings another interesting change that’s heavily related to Result (in fact it was implemented as part of the same Swift evolution proposal) — and that’s that the Error protocol is now self-conforming. That means that Error can now be used as a generic type that is constrained to having to conform to that same protocol, meaning that the above NSError-based technique is no longer necessary in Swift 5 — as we can simply use the Error protocol itself to anonymize errors:
For More information about the Result Type you can check the official Swift Doc by visiting below mention link:
Your email address will not be published. Required fields are marked*
Save my name email and website in this browser for the next time I comment.
Be the first to comment.
Enquiry or Requirement
If you have more details or questions, you can reply to the received confirmation email.