问题
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