2 ms·
Interesting idea. We can support unlimited cases by using tuples and varargs, though the fallback has to be the first argument if we don't want to return an opt
by bjustin 12y ago
Interesting idea. We can support unlimited cases by using tuples and varargs, though the fallback has to be the first argument if we don't want to return an optional:
func cond<T>(#fallback: T, testsAndExprs: (test: @auto_closure () -> Bool, expr: @auto_closure () -> T)...) -> T {
for (t, e) in testsAndExprs {
if t() {
return e()
}
}
return fallback
}
And in use:
// y is assigned "0 == 0, of course"
let y = cond(fallback: "fallback", (test: false, expr: "not this branch"), (test: 0 == 0, expr: "0 == 0, of course"))
- aardvark179 12y agoI was about to post something very similar, but was trying to check that type annotations can be applied to tulle components before posting. I do like the idea of @auto_closure, but I bet it will confuse the hell out people reading swift code unless the IDE highlights it in some way.
- terhechte 12y agoThat's a smart idea. Another option would be to use an Array, though that might make the types a bit ugly (as one would need to have the () -> Bool and () -> T in one array)