In Swift 5 several new features have been introduced. One of them is the Result type. The Result type in swift 5 is an enum that contains two cases: success and failure.

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

Result permite manejar errores para API asíncronas de una forma automática. Por ejemplo, para realizar una llamada a un servidor que devuelve una lista de usuarios (struct User), podemos implementar el siguiente método:

func fetchUsers(url: URL, completion: @escaping (Result<[User], Error>) -> Void) {
     URLSession.shared.dataTask(with: url) { data, response, error in
         guard let data = data, error == nil else {
             if let error = error as Error? {
                completion(.failure(error))
             }
             return
         }

         do {
             let users = try JSONDecoder().decode([User].self, from: data)
             completion(.success(users))
         } catch let error as? Error {
             completion(.failure(error))
         }

     }.resume()
 }

Now, we can call the fetchUsers method as follows:

let  url = 'FETCH_USERS_URL'

fetchUsers(url: url) { result in
    switch result {
        case .success(let users):
            // Código para tratar la información de los ususarios.
        case .failure(error):
            // Código para tratar los casos de error
    }
}
Categories: Swift

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Follow on Feedly
shares