[swift-evolution] [Idea] Switching Comparable types: a new operator

Jonathan Tang jonathan.d.tang at gmail.com
Thu Feb 4 17:36:21 CST 2016


Can't you define this yourself?  This worked in a Playground using Swift
2.1:

enum Ordering {
    case OrderedSame, OrderedAscending, OrderedDescending
}

infix operator <=> {}
func <=> <T: Comparable>(x: T, y: T) -> Ordering {
    if x < y {
        return .OrderedAscending
    } else if x > y {
        return .OrderedDescending
    } else {
        return .OrderedSame
    }
}


let x = 3
let y = 4
switch x <=> y {
case .OrderedSame:
    print(3)
case .OrderedAscending:
    print(4)  // Executed
case .OrderedDescending:
    print(5)
}

On Thu, Feb 4, 2016 at 12:52 PM, Ross O'Brien via swift-evolution <
swift-evolution at swift.org> wrote:

> Compare two values, and react differently if the first is larger, the
> second is larger, or they are equal.
>
> An if statement will result in an 'if { } else if { } else { }' structure.
> A switch can be used (case _ where x < y) but the compiler will complain
> that the switch is not exhaustive, resulting in a redundant 'default' case.
>
> I'd like to propose this addition to the Comparable type:
>
> infix operator <=> {}
>
> func <=> <C : Comparable> (lhs: C, rhs:C) -> NSComparisonResult
>
> {
>
> if lhs == rhs
>
> {
>
> return .OrderedSame
>
> }
>
> if lhs < rhs
>
> {
>
> return .OrderedAscending
>
> }
>
> return .OrderedDescending
>
> }
>
>
> This now allows code like this:
>
>
> let x = 3
>
> let y = 4
>
> switch x <=> y
>
> {
>
> case .OrderedSame:
>
> print(3)
>
> case .OrderedAscending:
>
> print(4)
>
> case .OrderedDescending:
>
> print(5)
>
> }
>
> -- Ross
>
> _______________________________________________
> 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/20160204/ee41ced0/attachment.html>


More information about the swift-evolution mailing list