Skip to content

Instantly share code, notes, and snippets.

@zarghol
Created November 25, 2019 12:20
Show Gist options
  • Save zarghol/cb331e9905b4cab41f5207086420cfbb to your computer and use it in GitHub Desktop.
Save zarghol/cb331e9905b4cab41f5207086420cfbb to your computer and use it in GitHub Desktop.
Resultify
enum ResultError: Error { case emptyData }
func resultify<T>(_ completion: @escaping (Result<T, Error>) -> Void) -> (T?, Error?) -> Void {
return { data, error in
if let error = error {
completion(.failure(error))
} else if let data = data {
completion(.success(data))
} else {
completion(.failure(ResultError.emptyData))
}
}
}
func resultify<T, U>(_ completion: @escaping (Result<(T?, U?), Error>) -> Void) -> (T?, U?, Error?) -> Void {
return { data1, data2, error in
if let error = error {
completion(.failure(error))
} else {
// with 2 parameters, we can't verify if there is no data :
// What to do when data1 is nil and not data2, and vice versa ?
completion(.success((data1, data2)))
}
}
}
// Use :
// 1. URLSession
let urlSession = URLSession(configuration: .default)
let url = URL(string: "https://google.com")!
urlSession.dataTask(with: url, completionHandler: resultify { result in
switch result {
case .failure(let error):
print("error : \(error)")
case .success(let success):
let data = success.0 // Data?
let response = success.1 // URLResponse?
}
})
// 2. CloudKit
let record = CKRecord(recordType: "Foo")
record["date"] = Date()
database.save(record, completionHandler: resultify { result in
switch result {
case .failure(let error):
print("error : \(error)")
case .success(let successedRecord): // CKRecord
print("saved : \(successedRecord)")
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment