我有一个文本字段,我想测试它的输入值是否为 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/