如何重构UITextField校验场景下的多guard语句以减少冗余代码?
iOS Swift 文本框校验代码精简方案
你可以通过「封装校验函数返回布尔值+遍历校验队列」的方式实现代码精简,同时100%保留原有校验逻辑:
步骤1:封装通用校验函数
将重复的校验逻辑抽离为独立函数,校验通过返回true,校验失败返回false,同时执行对应UI操作:
func validateTextField(_ textField: UITextField, targetWord: String) -> Bool { guard let inputText = textField.text, !inputText.isEmpty else { textField.showErrorMessage(message: "Please fill the field.") return false } guard inputText.contains(targetWord) else { textField.showErrorMessage(message: "Wrong word. Please check again.") return false } textField.hideErrorMessage() textField.setCorrectLayout() return true }
这里同时优化了原有代码重复判断文本非空的冗余逻辑,第一个guard已经保证输入不为空,后续无需二次判断。
步骤2:改写原有代理方法
将需要校验的文本框和对应目标词下标组成校验队列,按原有顺序遍历校验,任意一项校验失败直接退出外层方法:
func textFieldDidEndEditing(_ textField: UITextField) { // 按原有校验顺序配置待校验项 let checkItems = [ (firstTextField, words[firstWord - 1]), (secondTextField, words[secondWord - 1]), (thirdTextField, words[thirdWord - 1]), (fourthTextField, words[fourthWord - 1]) ] for (textField, targetWord) in checkItems { guard validateTextField(textField, targetWord: targetWord) else { confirmButton.disable(.filled) return } } confirmButton.enable(.filled) }
方案优势
- 逻辑完全对齐原有实现:还是按原有顺序校验,首个校验失败就终止流程、禁用按钮,和原来的guard return逻辑完全一致
- 冗余代码完全消除:后续新增文本框校验仅需在
checkItems数组中新增一行配置即可,无需重复编写校验逻辑 - 可维护性大幅提升:后续需要修改错误提示、校验规则仅需修改
validateTextField单处代码即可全局生效
内容的提问来源于stack exchange,提问作者user17019159
相关产品推荐
相关产品推荐

