Call completion Handler function using “Result”

Deadly 提交于 2020-06-17 22:55:51

问题


How to use call getEmployee function while using "Result"?

struct Employee {
    let name: String
    let designation: String
}

func getEmployee(name: String, completion: @escaping(Result<Employee?, Error>) -> Void) {

}

回答1:


First you need to make your structure conform to Codable

struct Employee: Codable {
    let name, designation: String
}

Than you need to fetch your data from your server and call completion if decoding was successful with your employee .success(employee) or if it fails pass failure with your error .failure(error):


func getEmployee(name: String, completion: @escaping(Result<Employee, Error>) -> Void) {
    URLSession.shared.dataTask(with: URL(string: "http://www.example.com/getEmployee.api?name=\(name)")!) { data, response, error in
        guard let data = data, error == nil else {
            if let error = error { completion(.failure(error)) }
            return
        }
        do {
            let employee = try JSONDecoder().decode(Employee.self, from: data)
            completion(.success(employee))
        } catch {
            completion(.failure(error))
        }
    }
}

Usage:

getEmployee(name: "Ella") { result in
    switch result {
    case let .success(employee):
        print("employee:", employee)
    case let .failure(error):
        print("error:", error)
    default: break
    }
}


来源:https://stackoverflow.com/questions/62205663/call-completion-handler-function-using-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!