// *** before: ***
func fetchOld(completion: @escaping (String?, Error?) -> Void) { }
fetchOld { text, error in
// two optionals give four states, and two of them cannot happen;
// still every caller checked them
if let error = error {
print(error)
} else if let text = text {
print(text)
}
}
// *** in version 5.0: ***
enum NetworkError: Error { case offline }
func fetch(completion: @escaping (Result<String, NetworkError>) -> Void) {
completion(.success("text"))
}
fetch { result in
switch result {
case .success(let text): print(text)
case .failure(let error): print(error)
}
}
// a throwing call turns into a Result and back
let result = Result { try String(contentsOfFile: "/etc/hosts") }
let value = try? result.get()
let length = result.map { $0.count }