Last active
October 26, 2022 19:59
-
-
Save antonyalkmim/75609916128160af396735087c6303b3 to your computer and use it in GitHub Desktop.
Iff + When Swift implementation
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
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