Sobes.tech
Junior — Middle

Can you explain what a Promise object is in Swift and how it is used to manage asynchronous operations?

sobes.tech AI

Answer from AI

In Swift, a Promise object represents an abstraction for managing asynchronous operations, allowing you to work with the result of an operation that may complete in the future.

A Promise contains a state (pending, fulfilled with a result, or rejected with an error) and provides methods to register handlers that will be called upon completion of the operation.

Using Promises enables writing cleaner and more readable asynchronous code, avoiding "callback hell".

Example of using a Promise (with the popular PromiseKit library):

import PromiseKit

func fetchData() -> Promise<String> {
    return Promise { seal in
        DispatchQueue.global().async {
            // simulate an asynchronous operation
            let success = true
            if success {
                seal.fulfill("Data received")
            } else {
                seal.reject(NSError(domain: "Error", code: 1, userInfo: nil))
            }
        }
    }
}

fetchData().done { data in
    print(data)
}.catch { error in
    print("Error: \(error)")
}

Thus, Promises in Swift help conveniently handle successful completion and errors of asynchronous operations.