Last active
April 23, 2021 10:39
-
-
Save VAndrJ/740ba04250348a67d2ddef913a1063ca to your computer and use it in GitHub Desktop.
Simple drop-in example for macOS command line tool project.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
infix operator ~>: MultiplicationPrecedence // Here we can create own group | |
// Composes two asynchronous functions | |
func ~> <T, U>( | |
_ first: @escaping (@escaping (Result<T, Error>) -> Void) -> Void, | |
_ second: @escaping (T, @escaping (Result<U, Error>) -> Void) -> Void) -> (@escaping (Result<U, Error>) -> Void | |
) -> Void { | |
return { result in | |
first { firstResult in | |
switch firstResult { | |
case .failure(let error): | |
result(.failure(error)) | |
case .success(let data): | |
second(data) { secondResult in | |
switch secondResult { | |
case .failure(let error): | |
result(.failure(error)) | |
case .success(let data): | |
result(.success(data)) | |
} | |
} | |
} | |
} | |
} | |
} | |
// MARK: - Example usage | |
func getUserId(_ completion: @escaping (Result<Int, Error>) -> Void) { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { | |
completion(.success(13)) | |
// completion(.failure(TestError.emptyUserId)) | |
} | |
} | |
func getUserFirstNameBy(id: Int, _ completion: @escaping (Result<String, Error>) -> Void) { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { | |
completion(.success("Volodymyr")) | |
// completion(.failure(TestError.userIsNoname)) | |
} | |
} | |
let dispatchGroup = DispatchGroup() | |
dispatchGroup.enter() | |
getUserId { result in | |
switch result { | |
case .failure(let error): | |
print(error.localizedDescription) | |
case .success(let id): | |
getUserFirstNameBy(id: id) { result in | |
switch result { | |
case .failure(let error): | |
print(error.localizedDescription) | |
case .success(let name): | |
print("Hi \(name)") | |
} | |
} | |
} | |
dispatchGroup.leave() | |
} | |
let chainedServices = getUserId(_:) ~> getUserFirstNameBy(id:_:) | |
dispatchGroup.enter() | |
chainedServices { result in | |
switch result { | |
case .failure(let error): | |
print(error.localizedDescription) | |
case .success(let name): | |
print("Hello again \(name)") | |
} | |
dispatchGroup.leave() | |
} | |
// MARK: - Additional for example | |
dispatchGroup.notify(queue: DispatchQueue.main) { | |
exit(EXIT_SUCCESS) | |
} | |
dispatchMain() | |
enum TestError: Error { | |
case emptyUserId | |
case userIsNoname | |
} | |
extension TestError: LocalizedError { | |
var errorDescription: String? { | |
switch self { | |
case .emptyUserId: | |
return "Empty user id" | |
case .userIsNoname: | |
return "User is noname" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment