为什么Int(false)有效,但Int(booleanVariable)不起作用?

G. *_*ika 3 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)'
Run Code Online (Sandbox Code Playgroud)

谁能解释这个事实?令人困惑。内部会发生什么?

vac*_*ama 5

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

Int.init(false)
Run Code Online (Sandbox Code Playgroud)

然后option单击init。您将看到它正在调用此初始化器:

init(_ number: NSNumber)
Run Code Online (Sandbox Code Playgroud)

由于false是有效的NSNumberNSNumber符合协议ExpressibleByBooleanLiteral,因此Swift会找到此初始值设定项。

那为什么不行呢?:

let emptyString = false
Int(emptyString)
Run Code Online (Sandbox Code Playgroud)

因为现在您传递的是Bool类型变量,Int并且没有带有的初始化程序Bool

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

您可以这样强制:

import Foundation // or import UIKit or import Cocoa
Int(emtpyString as NSNumber)
Run Code Online (Sandbox Code Playgroud)

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

  • 也许还要补充一点,这要求包含Foundation,`Int(false)`不会在纯Swift环境中编译。 (2认同)