Skip to content

Instantly share code, notes, and snippets.

@antonyalkmim
Last active October 26, 2022 19:59
Show Gist options
  • Save antonyalkmim/75609916128160af396735087c6303b3 to your computer and use it in GitHub Desktop.
Save antonyalkmim/75609916128160af396735087c6303b3 to your computer and use it in GitHub Desktop.
Iff + When Swift implementation
typealias IfResultClosure<Result> = (() -> Result)
typealias Case<Value, Result> = (Value, IfResultClosure<Result>)
@_functionBuilder
struct CaseBuilder<Value, Result> {
static func buildBlock(_ cases: Case<Value, Result>...) -> [Case<Value, Result>] {
cases
}
}
func If<Result>(_ predicate: Bool, then: IfResultClosure<Result>, `else`: IfResultClosure<Result?> = { nil }) -> Result? {
predicate ? then() : `else`()
}
func when<Value : Equatable, Result>(
_ predicate: Value,
@CaseBuilder<Value, Result> _ cases: () -> [Case<Value, Result>],
defaultValue: () -> Result
) -> Result {
cases().first { $0.0 == predicate }?.1() ?? defaultValue()
}
let whenResult = when("123") {
Case("1") {
"result 1"
}
Case("12") {
"result 12"
}
Case("123") {
"result 123"
}
} defaultValue: {
"My default value"
}
let isTrue = If(true) {
"something when true"
} else: {
"something when false"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment