ios - 如何在swift中将标签的文本保存为整数变量?

标签 ios swift casting option-type forced-unwrapping

我需要将我的标签的变化文本保存为一个变量,但是如果写下​​面的代码:

var warn = Int(self.dyn.text)

它说:

Value of optional type 'String?' must be unwrapped to a value of type 'String'
Coalesce using '??' to provide a default when the optional value contains 'nil'
Force-unwrap using '!' to abort execution if the optional value contains 'nil'

我应该使用什么代码?

最佳答案

var warn = Int(self.dyn.text ?? "") ?? 0

您必须提供一个默认值,以防无法转换为 Int。您还必须确保文本值不为零。

看看可选链和可选绑定(bind)

另一种方法是:

    if let dynText = self.dyn.text {
        if let warn = Int(dynText) {

            // warn is an available int variable here.
        }
    }

关于ios - 如何在swift中将标签的文本保存为整数变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53569392/

相关文章:

php - 如何从 Countable 对象中获取第一个元素?

c - strcat C 不打印和 int 到 char*

iphone - 无法提供测试账号,如何将需要登录的应用提交到AppStore?

android - Ionic/Cordova - AJAX 请求失败,状态代码为 -1

ios - 当文本字段更改时更改其他 View Controller 的变量

swift - [__NSCFTimer copyWithZone :]: unrecognized selector sent to instance

C++ 从类型 ‘void*’ 到类型 ‘double’ 的无效转换

android - 如何使用 Expo 在 native react 中打开默认联系人应用程序?

ios - Swift:如何将结构转换为字典以及键的层次结构

ios - 如何在swift中使用过滤功能