[swift-users] Bool to Int

Rick Mann rmann at latencyzero.com
Mon Nov 21 03:00:23 CST 2016


I'll try profiling it (or looking at the generated assembly).

Thanks!

> On Nov 20, 2016, at 21:15 , Marco S Hyman <marc at snafu.org> wrote:
> 
>> Is there a way that avoids branching?
> 
> Don’t know.  Have you profiled
> 
> let r = a > b ? 1 : 0
> 
> to know it is an issue?
>> 
>> So, according to Xcode, "true" and "a > b" both have type "Bool". I don't know why the compiler allows one and not the other, except that it's literal, and I guess there's a "BoolLiteralConvertible" (or equivalent) for the types.
> 
> You are including foundation which gets you the bridging code.
> 
> let r = Int(true)
> 
> is an error without foundation.  With foundation you get this:
> 
> extension NSNumber : ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral {
> 
>    // [snip]
> 
>    /// Create an instance initialized to `value`.
>    required public convenience init(booleanLiteral value: Bool)
> }
> 
> and this
> 
> extension Int {
> 
>    public init(_ number: NSNumber)
> }
> 
> 
> which when combined make `let r = Int(true)` work.  I haven’t profiled the code but would suspect that `let r = a > b ? 1 : 0` might be more efficient.
> 
> 


-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list