How use Result type in Swift Network?
About Result
Result type was introduced in Swift 5 for handling the network. Today we will learn how to use this in our project. Let’s first look at what this is
Result is enum type and it has two cases:
- Success
- Failure
I’ll use this API service: https://jsonplaceholder.typicode.com/posts
And I created a Test Project for us. Okay, it is enough, we going to show all of that on code :)
Usage
This is a model for handling the data (if you look at API address, you can see)
struct PostModel: Decodable {
let userId: String
let id: String
let title: String
let body: String
}
And this is ApiService
enum NetworkErrorConditions: Error {
case badUrl
case dataCannotHandled
}func fetchData(endPoint: String, completetion: @escaping (Result<NetworkModel, NetworkErrorConditions>) -> Void) { guard let url = URL(string: endPoint) else {
completetion(.failure(.badUrl))
} // request process and if success
completetion(.success(decodedData))}
Okay, guys, what is all of that, I want to explain this code:
Result<NetworkModel, NetworkErrorConditions>
if you remind we say Result has two cases: success and failure1. Success case: NetworkModel -> we get all of the posts successfully
p.s: you also can return another types like: String, Int, Float …2. Failure case: NetworkErrorConditions -> this is for handling any case of errors (it will be about decoding, bad URL, etc.)
In Swift, errors are represented by values of types that conform to the Error
protocol and in here also you’re seeing NetworkErrorConditions, this must conform with Error protocol.
And finally we ready to use our function:
fetchData(endPoint: "https://jsonplaceholder.typicode.com/posts") {
result in
switch result {
case .failure(let error):
switch error {
case .badUrl:
// your error message
case .dataCannotHandle:
// your error message
}
case .success(let decodedData):
// use your decodedData
}
}
You’ll see the request process and later we check our result if we detect any error in the request process we can handle it or if the request is success we get our data and use it.
Okay, the last thing I want to add our code :)
We can update our code for reusable, let me change our function to generic.
public func fetchData<T: Decodable>(endPoint: String, completetion: @escaping (Result<T, NetworkErrorConditions>) -> Void) {guard let url = URL(string: endPoint) else {
completetion(.failure(.badUrl))
}// request process and if success
completetion(.success(decodedData))}
In here, you can pass any of the data types for the request
Conclusion
Well done :) We learned how to use Result type for handling the network in swift. Hope you enjoyed this tutorial.
Thanks for reading and don’t forget to smile :)