“不推荐使用‘init’"Swift4 转换后的警告 [英] "'init' is deprecated" warning after Swift4 convert

查看:34
本文介绍了“不推荐使用‘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?

推荐答案

使用 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.使用 Intinit(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.使用 Intinit(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

这篇关于“不推荐使用‘init’"Swift4 转换后的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆