Skip to content

Instantly share code, notes, and snippets.

@rajivjhoomuck
Created March 30, 2021 22:10
Show Gist options
  • Save rajivjhoomuck/bd46fbd98b7f572047a386bcca1f08af to your computer and use it in GitHub Desktop.
Save rajivjhoomuck/bd46fbd98b7f572047a386bcca1f08af to your computer and use it in GitHub Desktop.
func canFail() -> Result<Int, Error> {
Bool.random()
? .success(7)
: .failure(NSError())
}
func neverFail() -> Result<Int, Never> { .success(9) }
func absurd<A>(_ never: Never) -> A {}
extension Result {
func fold<T>(ifSuccess: (Success) -> T, ifFailure: (Failure) -> T) -> T {
switch self {
case let .success(a): return ifSuccess(a)
case let .failure(e): return ifFailure(e)
}
}
}
let label1 = UILabel()
label1.text = canFail().fold(
ifSuccess: { "Received: \($0)" },
ifFailure: { "Fetch failed: \($0.localizedDescription)" }
)
let label2 = UILabel()
label2.text = neverFail().fold(
ifSuccess: { "Received: \($0)" },
ifFailure: absurd
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment