[swift-users] Bool to Int

Marco S Hyman marc at snafu.org
Sun Nov 20 23:15:58 CST 2016


> 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.




More information about the swift-users mailing list