Created
March 30, 2021 22:10
-
-
Save rajivjhoomuck/bd46fbd98b7f572047a386bcca1f08af to your computer and use it in GitHub Desktop.
This file contains 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 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