使用“结果”调用完成处理程序功能

时间:2020-06-04 23:16:27

标签: swift closures

在使用“结果”时如何使用调用getEmployee函数?

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

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

}

1 个答案:

答案 0 :(得分:1)

首先,您需要使您的结构符合Codable

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

如果您的员工.success(employee)解码成功,或者由于错误.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))
        }
    }
}

用法:

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