我想使用来自 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)")
}
Run Code Online (Sandbox Code Playgroud)
问题是代码无法编译,我收到不同的编译错误,例如:“二元运算符 '*' 不能应用于两个 'Double?' 操作数”。
出了什么问题?
Double(input1)
返回,String?
因为它不能保证工作。例如Double("1abc")
我们可以使用guard let
orif 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)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据您的评论,有多种方法可以在无效输入上显示“错误”,或显示最多 2 位小数点的答案。对于此示例,让我们将这两种情况
更改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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
PS:如果您想确保只能输入数字,那么您应该考虑.keyboardType(.decimalPad)
在TextField
s 上应用修饰符。
归档时间: |
|
查看次数: |
1586 次 |
最近记录: |