[swift-evolution] [Pitch] Add the sign method to the SignedNumberType protocol.
Haravikk
swift-evolution at haravikk.me
Tue May 24 06:33:10 CDT 2016
> On 23 May 2016, at 20:19, Dany St-Amant via swift-evolution <swift-evolution at swift.org> wrote:
>
> Challenge accepted… Removed the if/else if, at the cost of double function call to a tri-op:
>
> extension Bool {
> func as01<T:SignedNumberType>() -> T { return self ? 1 : 0 }
> }
>
> extension SignedNumberType {
> var sign: Self { return (self > 0).as01() - (self < 0).as01() }
> }
I don’t believe this solves the problem; I think you’ve really just moved the branching into the as01() method.
I think the more correct solution would be for all integer types to have a required Bool initialiser in a protocol somewhere, this way you could just do:
var sign:Self { return Self(boolValue: self > 0) - Self(boolValue: self < 0) }
Since all integer types should be able to do this by just extending the value to fit, rather than testing it. I’m not completely up-to-date on the integer changes that will be in Swift 3, but perhaps conversion from bool will be easier in future, in Swift 2.2 it’s not really treated as a number type for conversion purposes, which is disappointing.
Also apologies for my initial misunderstanding of the need for this sign property, no idea how I managed to get such a mental block as it’s obviously very useful for multiplication when account for sign and a few other cases. Anyway, I’m a +1, though implementation is definitely trickier than it seems it should be, thanks to some of Swift’s number-related quirks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160524/41290a30/attachment.html>
More information about the swift-evolution
mailing list