Swift

Result type in Swift 5

Result type

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 allows to handle errors for asynchronous APIs in an automatic way. For example, to make a call to a server that returns a list of users (struct User), we can implement the following method:

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):
            // Code to process user information.
        case .failure(error):
            // Code to handle error cases.
    }
}
Pinterest
LinkedIn
comments powered by Disqus

Related Posts

Pros and Cons of most used software architecture patterns A little over 6 years ago, on 2011, when I started learning to program applications for iOS, I used the Model View Controller (MVC) software architecture pattern (recommended by Apple), although it always ended up being a “Massive-View-Controller” architecture.

Currently, many applications receive information from the servers with which they connect in JSON format.

Advanced Swift Testing As you gain experience testing with Swift, you could encounter problems that are difficult to resolve using simple test cases.