In Swift 2.x I believe I could do:
let number = 1
let result = Bool(number)
print(result) // prints out: true
But since Swift 3 I've been unable to do this and it gives me the error:
Cannot invoke initialiser for type 'Bool' with an argument list of type '(Int)'
Currently I'm using an extension to convert an Int
to a Bool
but I was wondering if there isn't a build in option to do this.
There is no Boolean initializer that takes an
Int
, onlyNSNumber
. Previously, theInt
was implicitly bridged toNSNumber
through Foundation, but that was removed in Swift 3.You can do something like:
Or, you can extend
Bool
and create a custom init that takes an Int:Swift 5 try this
or
I'm using Xcode 9.0.1 and Swift 3.0.
which is working very well for me.
Swift 4
Swift 3
Usage
No, there is and has never been an explicit built in option for conversion of
Int
toBool
, see the language reference forBool
for details.There exists, still, however, an initializer by
NSNumber
. The difference is that implicit bridging between Swift numeric type andNSNumber
has been removed in Swift 3 (which previously allowed what seemed to be explicitBool
byInt
initialization). You could still access this byNSNumber
initializer by explicitly performing the conversion fromInt
toNSNumber
:As @Hamish writes in his comment below: if we leave the subject of initializers and just focus on the end result (instantiating a
Bool
instance given the value of anInt
instance) we can simply make use of the!=
operator forInt
values (specifically, the operator with signaturefunc !=(lhs: Int, rhs: Int) -> Bool
), a generalization easily achievable using the!=
operator approach:Much like you yourself as well as @JAL describes in his answer, you could construct your own
Bool
byInt
initializer, but you might as well consider generalizing this for any type conforming to theInteger
protocol: