[swift-evolution] [Pitch] Add the sign method to the SignedNumberType protocol.

Adrian Zubarev adrian.zubarev at devandartist.com
Sun May 22 03:27:14 CDT 2016


This should do the trick:

extension SignedNumberType {
     
    var sign: Self {
         
        if self == (0 as Self) {
            return (0 as Self)
        } else if self > (0 as Self) {
            return (1 as Self)
        }
        return (-1 as Self)
    }
}


-- 
Adrian Zubarev
Sent with Airmail

Am 22. Mai 2016 bei 09:08:37, Adam Nemecek via swift-evolution (swift-evolution at swift.org) schrieb:

Howdy,
I think that the SignedNumberType should implement a method called sign that will return -1 for negative numbers, 0 for 0 and 1 for positive numbers. This is similar to the signum method in e.g. Java and similarly called methods in other languages.

The implementation is fairly straight forward

extension SignedNumberType {
  var sign: Self {
    if self == 0 {
      return 0
    }
    else if self > 0 {
      return 1
    }
    return -1
  }
} 

I was trying to implement is without branching by doing (x > 0) - (x < 0) but I couldn't get the types right so I'm open to suggestions.


_______________________________________________
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/20160522/c0664c26/attachment.html>


More information about the swift-evolution mailing list