News for hackers. Stuff that matters.
Re:Using ‘switch’ to match arbitrary logic instead of string... by Razengan on Monday August 19, 2019 @07:51AM (#20736926)
EDIT: Oops, chalk this up as another case of reinventing the wheel. We already have all this in the form of the ?: ternary operator, as masklinn pointed out:

https://news.ycombinator.com/item?id=20736714

----

Inspired by this, I cooked up a crude imitation in (ugly/functional'ish?) Swift:

    let result = [(firstCheck,  1),
                  (secondCheck, 2),
                  (thirdCheck,  3)]
                  .first { $0.0() }?.1
That iterates over an array of (() - > Bool, Value) tuples and returns the second element of the first tuple whose first element is a function that returns true, otherwise nil. The types of all values must be the same. Could shorten .first to .firstTrue or something.

And a version that's closer to your idea:

    typealias BooleanFunction = () -> Bool
    typealias FunctionValuePair<ResultType> = (BooleanFunction, result: ResultType)

    func pickOne<ResultType> (_ pairs: FunctionValuePair<ResultType>...) -> ResultType? {
        pairs.first { function, result in
            function() == true
        }?.result
    }

    let result = pickOne(
        (firstCheck,  "one"),
        (secondCheck, "two"),
        (thirdCheck,  "three"))
        ?? "default"
You could make the default result an argument for pickOne so that it never returns nil, but I prefer to keep it an optional.

Though it's too early in my day to think of better names. :)

There are no comments on this comment yet.