ios - 计算多个 uitextfields 结果的最佳方法

标签 ios swift uitextfield

我正在实现一个应用程序,它有一个按钮,可以将 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 收集到数组文字中,并使用 flatMapreduce 转换值并生成总和:

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/

相关文章:

iphone - iOS SDK : How can I check if a port is open?

ios - 如何让detailViewController 在Swift 的masterViewController.tableView 中显示上一行或下一行的detailItem?

ios - 如何在 Swift 中淡入和淡出 ActivityIndi​​cator?

objective-c - 如何使用 NSNumberFormatter 格式化 UITextField?

ios - 清除文本后如何在 TextFields 中添加 PlaceHolder

ios - 如何停止函数在 Swift 3.0 中运行

ios - FFmpeg 将流保存到 mp3

swift - iOS 14 WidgetKit : Widget not rendering when list is used

ios - 完成处理程序 Swift 3

ios - 自定义清除按钮