[swift-users] Bool to Int

Marco S Hyman marc at snafu.org
Mon Nov 21 17:09:59 CST 2016


> Except it does, because if I write
> 
> 	let a = 2

> a is of type Int (at least, according to Xcode's code completion).

and if you write

	let b = 2 + 0.5

2 is treated as a double. The type of the literal “2” varies with context. Do you also find that inconsistent and confusing? 

> But this gives inconsistent results:
> 
> 	let t = true
> 
> 	let a = Int(true)
> 	let b = Int(t)		//  Error
> 
> I find this to be very inconsistent and confusing.

t is a Bool and there is no automatic conversion from Bool to Int.

true is not a Bool.  It may be treated as a Bool depending upon context.  In the line `let t = true` it is treated as a Bool. In `let a = Int(true)` it is treated as an NSNumber (assuming you import foundation).

Marc


More information about the swift-users mailing list