Last active
October 8, 2020 10:43
-
-
Save rojanDinc/4eec199d2f709fae838b6ecec791db42 to your computer and use it in GitHub Desktop.
Swift Result extensions
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
extension Result { | |
func isSuccess() -> Bool { | |
switch self { | |
case .success(_): return true | |
case .failure(_): return false | |
} | |
} | |
func apply(_ f: (Success) -> ()) -> Result<Success, Failure> { | |
if case let .success(s) = self { | |
f(s) | |
} | |
return self | |
} | |
func applyError(_ f: (Failure) -> ()) -> Result<Success, Failure> { | |
if case let .failure(err) = self { | |
f(err) | |
} | |
return self | |
} | |
func filter(_ predicate: (Success) -> Bool, ifFalse: (Success) -> Failure) -> Result<Success, Failure> { | |
switch self { | |
case .success(let val): return predicate(val) ? .failure(ifFalse(val)) : .success(val) | |
case .failure(let err): return .failure(err) | |
} | |
} | |
} |
Lolwat? :o
Hell yeah
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cred goes to @nyaray