为什么Int(false)工作但Int(booleanVariable)不工作?

时间:2016-11-29 13:57:45

标签: swift swift3

以下代码:

Int(false) // = 1, it's okay

//but when I try this
let emptyString = true //or let emptyString : Bool = true
Int(emptyString) //error - Cannot invoke initializer with an argument list of type '(Bool)'

任何人都可以解释这个事实吗?这令人困惑。里面发生了什么?

4 个答案:

答案 0 :(得分:4)

要了解Int(false)发生了什么,请将其更改为:

Int.init(false)

然后选项 - 点击init。您将看到它正在调用此初始值设定项:

init(_ number: NSNumber)

由于false是有效的NSNumberNSNumber符合协议ExpressibleByBooleanLiteral,因此Swift会找到此初始化程序。

那为什么这不起作用?:

let emptyString = false
Int(emptyString)

因为现在您传递了一个Bool类型的变量而Int没有一个带Bool的初始值设定项。

在Swift 2中,这可行,因为Bool自动桥接到NSNumber,但已被删除。

你可以这样强迫它:

import Foundation // or import UIKit or import Cocoa
Int(emtpyString as NSNumber)

仅在导入Foundation时才有效。在Pure Swift中,当然没有NSNumber

答案 1 :(得分:0)

试试这个

let intValue = emptyString ? 1 : 0

更新

您想使用Int(),请使用此

Int(NSNumber(value:emptyString))

答案 2 :(得分:0)

Int没有Bool作为参数的初始化。

答案 3 :(得分:0)

你确定你的代码库中某处没有这样的东西:

extension Int : ExpressibleByBooleanLiteral {
    public init(booleanLiteral: BooleanLiteralType) {
        self = booleanLiteral ? 1 : 0
    }
}

因为否则,let foo = Int(false)之类的行不应该编译。

相关问题