[swift-users] Bool to Int

Kenny Leung kenny_leung at pobox.com
Mon Nov 21 11:46:11 CST 2016


This is so confusing. "Literals are untyped", but there’s a “BooleanLiteral”, which is obviously of type Boolean.

-Kenny


> On Nov 21, 2016, at 2:49 AM, Adrian Zubarev via swift-users <swift-users at swift.org> wrote:
> 
> In general this is a correct behaviour, because literals in Swift are untyped. Int does not have any initializer for a Bool so the compiler tries to find a type that might conforms to ExpressibleByBooleanLiteral for all possible initializer of Int (Int.init(_: TYPE)). This resolution decides to go with NSNumber in your case?!
> 
> The thing is, when you write Int(a > b), you’re passing a Bool and not a literal anymore. Here the compiler does not fallback to NSNumber anymore and reports you an error, because Int.init(_: Bool) does not exist. 
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 21. November 2016 um 04:48:35, Rick Mann via swift-users (swift-users at swift.org) schrieb:
> 
>> It seems I can't do this:
>> 
>> let r = Int(a > b)
>> 
>> but I can do it with a literal:
>> 
>> let r = Int(true)
>> 
>> I'd like to do this to implement signum without branching, but perhaps that's not possible.
>> 
>> -- 
>> Rick Mann
>> rmann at latencyzero.com
>> 
>> 
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list