我想使用来自 2 个不同文本字段的输入进行计算,并将输出放在一个文本中。见代码:
@State var input1: String = ""
@State var input2: String = ""
var calculation : Double {
let calculationProduct = Double(input1) * Double(input2)
return calculationProduct
}
var body: some View {
VStack{
TextField("", text: $input1)
TextField("", text: $input1)
Text("\(calculation)")
}
问题是代码无法编译,我得到不同的编译错误,例如:“Binary operator '*' cannot be applied to two 'Double?'操作数”。
出了什么问题?
最佳答案
Double(input1)
返回 String?
因为它不能保证工作。例如双(“1abc”)
我们可以使用 guard let
或 if let
甚至 nil 合并运算符 ??
来处理这个问题。但对于下面的示例,我们将使用 guard let
优雅地处理它。
struct ContentView: View {
@State var input1: String = ""
@State var input2: String = ""
var calculation : Double {
guard let m = Double(input1), let n = Double(input2) else { return 0 }
return m * n
}
var body: some View {
VStack {
TextField("", text: $input1)
TextField("", text: $input2)
Text("\(calculation)")
}
}
}
编辑
根据您的评论,有多种方法可以在无效输入或小数点后两位的答案上显示“错误”。
对于这个例子,让我们在这两种情况下将 result
更改为计算的 String
属性,如下所示:
struct ContentView: View {
@State var input1: String = ""
@State var input2: String = ""
var calculation: String {
//check if both fields have text else no need for message
guard input1.isEmpty == false, input2.isEmpty == false else { return "" }
//check if both are numbers else we need to print "Error"
guard let m = Double(input1), let n = Double(input2) else { return "Error" }
let product = m * n
return String(format: "%.2f", product)
}
var body: some View {
VStack {
TextField("Enter First Number", text: $input1)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Enter Second Number", text: $input2)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text(calculation)
}
}
}
PS:如果你想确保只能输入数字,那么你应该考虑在 TextField
上应用 .keyboardType(.decimalPad)
修饰符。
关于ios - 使用文本字段输入 SwiftUI 阅读和计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61329716/