Created
September 25, 2020 17:45
-
-
Save k-marin/430716b3148c3a0b163e1b8d9ae5560e to your computer and use it in GitHub Desktop.
Swift when-then-else
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
// Just an experiment for composing if else in a more structured way | |
// usage | |
var isLoadMoreAllowed = false | |
func loadMore() { | |
print("loading more") | |
} | |
when(isLoadMoreAllowed) | |
.then { loadMore() } | |
.else { print ("do something else") } | |
// implementation | |
// global function | |
func when(_ bool: Bool) -> Bool.Some { | |
Bool.Some(bool: bool) | |
} | |
// Bool extension | |
extension Bool { | |
struct Some { | |
fileprivate let bool: Bool | |
@discardableResult | |
func then(_ execute: () -> Void) -> Bool.Some { | |
guard bool else { return self } | |
execute() | |
return self | |
} | |
@discardableResult func `else`(_ execute: () -> Void) -> Bool.Some { | |
guard bool else { | |
execute() | |
return self | |
} | |
return self | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment