[swift-evolution] ? suffix for <, >, <=, >= comparisons with optionals to prevent subtle bugs

Jacob Bandes-Storch jtbandes at gmail.com
Thu Dec 3 18:40:03 CST 2015


To me it seems logical that comparing Optional<Int> with Int (or another
Optional<Int>), if it's allowed at all, should return Optional<Bool>. Since
conditional statements only accept Bool, the user is forced to handle the
nil case explicitly.

Jacob

On Thu, Dec 3, 2015 at 4:33 PM, Kevin Ballard <kevin at sb.org> wrote:

> I completely disagree. Being able to compare `Optional` values is very
> handy in a lot of cases. Adding special syntax for this is just unnecessary
> language complication, especially as the proposed syntax conflicts with the
> existing meaning of the postfix-? operator and the optional-chaining
> operator.
>
> -Kevin Ballard
>
> On Thu, Dec 3, 2015, at 04:17 PM, Jacob Bandes-Storch wrote:
>
> Agreed — or, I think, these operators could/should simply be removed.
>
> I filed <rdar://22833869> about this a while ago, which was marked as
> Duplicate/<rdar://16966712>.
>
>
> Summary:
> This returns true:
>     (nil as Int?) < 0
> This also returns true, which makes even less sense:
>     (nil as Int?) < Int.min
>
>
> Expected Results:
> nil < 0, nil > 0, and nil == 0, should all be false. nil != 0 should be true.
> Alternatively, just *don't* provide < and > operators that accept optional arguments.
>
>
> Actual Results:
> nil < 0 is true. Others are as expected.
>
>
> See also: https://twitter.com/jtbandes/status/646914031433871364
>
>
> Jacob
>
> On Thu, Dec 3, 2015 at 3:42 PM, Amir Michail <a.michail at me.com> wrote:
>
> Such comparisons with optionals can result in hard to find bugs.
>
> For example consider:
>
> let f = x < 5  // x is of type Int? and may be nil
>
> The proposed ? suffix would be used as follows and makes the possibility
> of nil very clear:
>
> let f = x? < 5
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> *_______________________________________________*
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151203/81254b24/attachment-0001.html>


More information about the swift-evolution mailing list