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

Haravikk swift-evolution at haravikk.me
Wed May 25 11:13:53 CDT 2016


> On 25 May 2016, at 16:51, Jeremy Pereira <jeremy.j.pereira at googlemail.com> wrote:
>> 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?

Shouldn’t have to but possibly yeah; the booleans are just 1-bit values, so they can be extended to fit any integer type, but currently the ability to convert them seems lacking. There’s supposed to be something being done about improving the ability to use numeric types interchangeably (e.g- you should be able to freely fire an Int16 into an Int32 with implicit casting since it definitely fits), but I don’t know if Bool will be included in that or not.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160525/db6adcd1/attachment.html>


More information about the swift-evolution mailing list