我正在实现一个应用程序,它有一个按钮,可以将 4 个 uitextfields 的内容相加。我的问题是“如何知道哪些 uitextfields 是空的?”
我想确保在按下按钮时如果 uitextfield 具有值,则不会忽略它。 普通的 if 语句可以解决问题吗?例如:
if(textfield1 is not empty && textfield2 is not empty &&... && textfield4 is not empty) {
// add them together
}else if (choose one textfield to check if its empty) {
// sign the empty textfield to 0 and add the rest
} else if (choose another textField to check if its empty) {
// sign the empty textfield to 0 and add the rest
}
.
.
.
// end of button block
对我来说,这种方法在逻辑上和编程上都不是一个好方法。
完成这项任务的最佳方法是什么?
谢谢
最佳答案
您可以充分利用nil 合并运算符 ??
来处理文本字段为空或不包含合法值的情况:
let value1 = Int(textfield1.text ?? "") ?? 0
let value2 = Int(textfield2.text ?? "") ?? 0
let value3 = Int(textfield3.text ?? "") ?? 0
let value4 = Int(textfield4.text ?? "") ?? 0
let sum = value1 + value2 + value3 + value4
或者对于函数式方法,将 textfield
收集到数组文字中,并使用 flatMap
和 reduce
转换值并生成总和:
let values = [textfield1, textfield2, textfield3, textfield4].flatMap({$0.text}).flatMap({Int($0)})
let sum = values.reduce(0, +)
关于ios - 计算多个 uitextfields 结果的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657410/