[swift-evolution] [Pitch] Use "where" in combination with "??" to provide Ternary-like functionality
Charles Constant
charles at charlesism.com
Mon May 23 00:23:50 CDT 2016
Would anyone be interested in "where" (or a similar keyword or operator)
being able to do this:
*let val = "foo" where true* // "foo"
*let val = "foo" where false* // nil
... and therefore being able to work in conjunction like this:
* let val = *
* "positive" where ( val > 0 ) ?? *
* "negative" where ( val < 0 ) ?? *
* "zero"*
In other words, a statement that given a value and a bool, and returns the
value if the bool is true, but nil if the bool is false.
There have been a few threads here about "switch assignment" and "extended
ternary" statements. I encounter frustrations regularly when I want to
write concise, but easy-to-read code for conditions that require more to
than two options. We have discussed problems using dicts, enums, etc in the
past.
The problem with most of the suggestions so far is that they aren't very
Swifty. But if "where" worked the way I'm pitching, a coder could impliment
most of the alternatives we've discussed (by using autoclosure, and custom
operators). Eg:
* let val:FooEnum = depends( bar ){*
* .Red where $0 == .A ?? *
* .Blue where $0 == .B ?? *
* .Green where $0 == .C ?? *
* .None*
* }*
This strikes me as the least disruptive, and most Swifty solution.
Would this appeal to anyone else?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160522/2f9633e9/attachment.html>
More information about the swift-evolution
mailing list