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

Jeremy Pereira jeremy.j.pereira at googlemail.com
Wed May 25 10:51:55 CDT 2016


> On 24 May 2016, at 12:33, Haravikk via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> 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) }

Aren’t you just hiding the branches in the initialiser there?

> 



More information about the swift-evolution mailing list