-
-
Save dreymonde/a3ed6b6040fde28dcba4a13e4dc23e2f to your computer and use it in GitHub Desktop.
Better completion blocks by using higher order functions
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
func completion<Result>(onResult: @escaping (Result) -> Void, onError: @escaping (Error) -> Void) -> ((Result?, Error?) -> Void) { | |
return { (maybeResult, maybeError) in | |
if let result = maybeResult { | |
onResult(result) | |
} else if let error = maybeError { | |
onError(error) | |
} else { | |
onError(SplitError.NoResultFound) | |
} | |
} | |
} | |
// Use where a completion block will give a `Bool` value indicating it was successful or not. | |
func completion(onSuccess: @escaping () -> Void, onFailure: @escaping () -> Void) -> ((Bool) -> Void) { | |
return { success in | |
if (success) { | |
onSuccess() | |
} else { | |
onFailure() | |
} | |
} | |
} | |
enum SplitError: Error { | |
case NoResultFound | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment