将Int转换为Bool [英] Converting Int to Bool
问题描述
在Swift 2.x中我相信我能做到:
In Swift 2.x I believe I could do:
let number = 1
let result = Bool(number)
print(result) // prints out: true
但是自从Swift 3以来我一直无法做到这一点并且它给了我错误:
But since Swift 3 I've been unable to do this and it gives me the error:
无法调用类型'Bool'的初始化程序
类型的参数列表'(Int)'
Cannot invoke initialiser for type 'Bool' with an argument list of type '(Int)'
目前我正在使用扩展名来转换 Int
到 Bool
但是我想知道是否没有构建选项来执行此操作。
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.
推荐答案
不,从来没有明确的内置选项将 Int
转换为 Bool
,请参阅 <$ c的语言参考$ c> Bool 了解详情。
No, there is and has never been an explicit built in option for conversion of Int
to Bool
, see the language reference for Bool
for details.
但是,仍然存在初始化程序 NSNumber
。区别在于Swift数字类型与 NSNumber
之间的隐式桥接已在Swift 3中删除(之前允许显式为 Bool
by Int
初始化)。您仍然可以通过显式执行从 Int
到 NSNumber <的转换,通过
NSNumber
初始化程序访问它/ code>:
There exists, still, however, an initializer by NSNumber
. The difference is that implicit bridging between Swift numeric type and NSNumber
has been removed in Swift 3 (which previously allowed what seemed to be explicit Bool
by Int
initialization). You could still access this by NSNumber
initializer by explicitly performing the conversion from Int
to NSNumber
:
let number = 1
let result = Bool(number as NSNumber)
print(result) // true
正如@Hamish在下面的评论中写道:如果我们离开初始化器的主题并只关注最终结果(实例化 Bool
实例给定 Int $ c $的值c>实例)我们可以简单地使用
!=
运算符来获取 Int
值(具体来说,带签名的运算符) func!=(lhs:Int,rhs:Int) - > Bool
),使用轻松实现的概括!=
算子方法:
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 an Int
instance) we can simply make use of the !=
operator for Int
values (specifically, the operator with signature func !=(lhs: Int, rhs: Int) -> Bool
), a generalization easily achievable using the !=
operator approach:
let number = -1
let result = number != 0
print(result) // true
很像你自己以及 @ JAL在他的答案中描述,您可以通过 Int
构建自己的 Bool
初始化程序,但您也可以考虑对符合 整数的任何类型进行概括。
协议:
Much like you yourself as well as @JAL describes in his answer, you could construct your own Bool
by Int
initializer, but you might as well consider generalizing this for any type conforming to the Integer
protocol:
extension Bool {
init<T: Integer>(_ num: T) {
self.init(num != 0)
}
}
/* example usage */
let num1: Int8 = -1
let num2: Int = 3
let num3: UInt64 = 0
// ....
let result1 = Bool(num1) // true
let result2 = Bool(num2) // true
let result3 = Bool(num3) // false
这篇关于将Int转换为Bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!