[swift-users] Bool to Int

Adrian Zubarev adrian.zubarev at devandartist.com
Mon Nov 21 11:52:08 CST 2016


A literal doesn’t have a type on its own. Instead, a literal is parsed as having infinite precision and Swift’s type inference attempts to infer a type for the literal.

Source


-- 
Adrian Zubarev
Sent with Airmail

Am 21. November 2016 um 18:46:32, Kenny Leung via swift-users (swift-users at swift.org) schrieb:

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

_______________________________________________
swift-users mailing list
swift-users at swift.org
https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161121/1495f11f/attachment.html>


More information about the swift-users mailing list