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

Ross O'Brien narrativium+swift at gmail.com
Thu Feb 4 14:52:39 CST 2016


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160204/808aa26d/attachment.html>


More information about the swift-evolution mailing list