“不推荐使用‘init’"Swift4 转换后的警告
问题描述:
在 Swift3 中,我之前使用以下方法将 Bool 转换为 Int
In Swift3, I previously converted a Bool to an Int using the following method
let _ = Int(NSNumber(value: false))
转换为 Swift4 后,我收到'init' is deprecated"警告.还应该怎么做?
After converting to Swift4, I'm getting a "'init' is deprecated" warning. How else should this be done?
答
#3.使用
#4.使用
使用 Swift 4.2 和 Swift 5,您可以选择以下 5 种解决方案之一来解决您的问题.
With Swift 4.2 and Swift 5, you can choose one of the 5 following solutions in order to solve your problem.
import Foundation
let integer = NSNumber(value: false).intValue
print(integer) // prints 0
#2.使用类型转换
import Foundation
let integer = NSNumber(value: false) as? Int
print(String(describing: integer)) // prints Optional(0)
#3.使用 Int
的 init(exactly:)
初始化器
import Foundation
let integer = Int(exactly: NSNumber(value: false))
print(String(describing: integer)) // prints Optional(0)
作为前面代码的替代,您可以使用下面更简洁的代码.
As an alternative to the previous code, you can use the more concise code below.
import Foundation
let integer = Int(exactly: false)
print(String(describing: integer)) // prints Optional(0)
#4.使用 Int
的 init(truncating:)
初始化器
import Foundation
let integer = Int(truncating: false)
print(integer) // prints 0
#5.使用控制流
注意以下示例代码不需要导入 Foundation.
#5. Using control flow
Note that the following sample codes do not require to import Foundation.
用法 #1(if 语句):
let integer: Int
let bool = false
if bool {
integer = 1
} else {
integer = 0
}
print(integer) // prints 0
用法#2(三元运算符):
let integer = false ? 1 : 0
print(integer) // prints 0