[swift-evolution] [Pitch] Use "where" in combination with "??" to provide Ternary-like functionality

Charles Constant charles at charlesism.com
Mon May 23 23:24:08 CDT 2016


Right... per "[swift-evolution] [Idea] Find alternatives to `switch self`"
 it was only "impossible" in my head.

Thanks Dany

This proposal is unnecessary.

On Mon, May 23, 2016 at 8:53 PM, charles at charlesism.com <
charlesism.com at gmail.com> wrote:

> I'm not actually familiar with the term "tri op" but if you're referring
> to the ternary, it's only useful when you two, or three items.
>
> If you chain a ternary to use more than three options it becomes
> error-prone and almost impossible for a human to read
>
> When I'm at my desktop I'll add a couple better examples of what I'm
> proposing.
>
> Sent from my iPhone
>
> On May 23, 2016, at 6:18 PM, Dany St-Amant <dsa.mls at icloud.com> wrote:
>
>
> Why reinvent the wheel, when the old trusty (but a bit cryptic according
> to some) tri-op can do the trick…
>
> Le 23 mai 2016 à 04:29, Charles Constant via swift-evolution <
> swift-evolution at swift.org> a écrit :
>
> Here's a few examples of what this change would allow.
>
> I just plucked the first instances of other people's switch statements
> that I found on GitHub.
>
> If there were an easy way to search GitHub for chained ternary
> expressions, I would have added some examples of those too, since they
> could all be improved with this where clause + ??.
>
>
> mutating func toggle() {
> switch self{
> case Off:
> self = On
> case On:
> self = Off
> }
> }
>
>
>
> mutating func toggle() {
> self = .On where (self == .Off) ?? .Off
> }
>
>
> mutating func toggle() { self = self == .Off ? .On : .Off }
>
>
> switch switchNumberThree {
> case 10, 11, 12:
> println("It is \(switchNumberThree)")
> default:
> ("It is none of them!")
> }
>
>
> println(
> "It is \(switchNumberThree)" where 10...12 ~= switchNumberThree
> ?? "It is none of them!"
> )
>
>
> print( 10...12 ~= switchNumberThree ? "It is \(switchNumberThree)"
>        : "It's none of them" )
>
>
> switch x {
> case 1:
> j++
> case 2:
> j++
> case 3:
> j++
> case 4:
> j++
> fallthrough
> case 5:
> j++
> fallthrough
> default:
> j++
> }
>
>
> j = j+1 where (4...5 ~= x) ?? j+2
>
>
> Broken conversion:
> j += 4...5 ~= x ? 1 : 2
>
> Proper conversion:
> j += 4 ~= x ? 3 : 5 ~= x ? 2 : 1
>
> Earlier e-mail example:
>
> *    let foo = *
> *        "positive" where ( bar > 0 )  ?? *
> *        "negative" where ( bar < 0 ) ?? *
> *        "zero"*
>
>
> let foo = bar > 0 ? "positive" :
>           bar < 0 ? "negative" :
>           "zero"
>
> Dany
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160523/f59faf4a/attachment.html>


More information about the swift-evolution mailing list