Skip to content

Instantly share code, notes, and snippets.

@dreymonde
Forked from amlcurran/Completion.swift
Created February 27, 2017 23:26
Show Gist options
  • Save dreymonde/a3ed6b6040fde28dcba4a13e4dc23e2f to your computer and use it in GitHub Desktop.
Save dreymonde/a3ed6b6040fde28dcba4a13e4dc23e2f to your computer and use it in GitHub Desktop.
Better completion blocks by using higher order functions
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