Skip to content

Instantly share code, notes, and snippets.

@k-marin
Created September 25, 2020 17:45
Show Gist options
  • Save k-marin/430716b3148c3a0b163e1b8d9ae5560e to your computer and use it in GitHub Desktop.
Save k-marin/430716b3148c3a0b163e1b8d9ae5560e to your computer and use it in GitHub Desktop.
Swift when-then-else
// 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