swift - 如何测试一个值是否是Int类型

标签 swift string swiftui types integer

我有一个文本字段,我想测试它的输入值是否为 Int 类型。

代码如下:

import SwiftUI

struct ContentView: View {
    @State var integer: String = ""
    
    var body: some View {
        TextField("Enter an integer", text: $integer)
        
        Button(action: {
            if (Int(integer)//here is where I want to figure out whether the value is of type Int) {
                print("Yay")
            } else {
                print("not an integer")
            }
        }, label: {
            Text("Check")
        })
    }
}

必须有一个简单的方法来做到这一点,但我一直无法弄清楚。

最佳答案

简单的空检查就可以了。

Button(action: {
    if Int(integer) != nil {
        print("Yay")
    } else {
        print("not an integer")
    }
}, label: {
    Text("Check")
})

或者使用可选绑定(bind)

Button(action: {
    if let numInt = Int(integer) {
        print("Yay")
        print(numInt)
    } else {
        print("not an integer")
    }
}, label: {
    Text("Check")
})

关于swift - 如何测试一个值是否是Int类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74907556/

相关文章:

ios - 迁移到 Swift 2 后出现 UIActivityViewController 错误

ios - 返回根导航 Controller 的按钮

ios - 使 UIView 可滚动和可缩放

javascript - 在Javascript中添加到对象时,如何使显示为数组的字符串返回数组

c - 合并算法在合并时对两个字符串数组进行排序

javascript - 字符串数组的字符串操作

navigation - SwiftUI Scrollview 破坏了 NavigationLink 行为

swift - 如何在 Ventura 13.3.1 中使用 SwiftUI 将图像设置为 MacCatalyst 上的菜单标签

ios - 动画 UIViews 时的奇怪效果

crash - 获取 CGRect View