[swift-evolution] ternary operator ?: suggestion
David Waite
david at alkaline-solutions.com
Thu Dec 24 00:39:18 CST 2015
My only issue (barring any longer term plan to move toward everything being an expression) is that the question mark already has many uses in the language. If we aren’t supporting the C-style ternary operator syntax, I don’t know if there is a good reason anymore to use ‘?’ considering its heavy use around optionals.
-DW
> On Dec 23, 2015, at 2:05 PM, Rainer Brockerhoff via swift-evolution <swift-evolution at swift.org> wrote:
>
> On 22/12/15 16:50 , swift-evolution-request at swift.org wrote:
>> Date: Tue, 22 Dec 2015 10:07:26 -0800
>> From: Jordan Rose <jordan_rose at apple.com>
>> To: Thorsten Seitz <tseitz42 at icloud.com>
>> Message-ID: <2D35F5BD-3DDF-43C3-A461-14FB65530BEF at apple.com>
>>
>> I think this is a good point. We definitely want to keep the boolean
>> ternary operator compact for the simple cases, and that may be at
>> odds with a general switch expression (with multi-case pattern
>> match).
>
> +1 for a compact form.
>
> I use the boolean ternary a lot, and I'd really dislike complicating it
> with keywords or expanding it into a multiline construct with cases.
>
> Nesting is of course its main problem.
>
>
>> Date: Tue, 22 Dec 2015 10:53:50 -0800
>> From: Paul Ossenbruggen <possen at gmail.com>
>> Message-ID: <7C5ECA99-4527-4995-8503-215F294CCB64 at gmail.com>
>>
>> • it is hard to tell when a ternary begins and ends, especially when nested.
>
> At first I liked Paul's original proposal of
> let a = ?(x == y: a, b)
> but I now think something intermediate like
> let a = x == y ?(a, b)
> would look better; it does take care of nesting. For more clarity one
> could always write
> let a = (x == y) ?(a, b)
>
>> • It is not until you get to the question mark that you realize it is a ternary.
>
> I think that's actually a good thing. You (or the parser) have found a
> boolean expression and when the ?( appears you understand the result is
> fed into a selector. Were the ? and ( separate you could consider ? as a
> binary operator accepting a boolean and a 2-tuple.
>
> Today, using ? as an operator appears not to be allowed, but
> public func ??<T> (left:Bool, right: (T, T)) -> T {
> if (left) {
> return right.0
> }
> return right.1
> }
> already works:
> let a = (x == y) ?? (a, b)
> runs as expected. Downside, no @autoclosure on tuple items.
>
> IOW, you shouldn't be too surprised finding a binary operator after an
> expression :-)
>
> --
> Rainer Brockerhoff <rainer at brockerhoff.net>
> Belo Horizonte, Brazil
> "In the affairs of others even fools are wise
> In their own business even sages err."
> http://brockerhoff.net/blog/
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list