我有几个文本字段,每个文本字段具有不同数量的最大字符。如何将if分支更改为枚举并使用switch?
//if -> switch
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength = (textField.text ?? "").count + string.count - range.length
if(textField == textFieldA) {
return newLength <= 6
}
if(textField == textFieldB) {
return newLength <= 7
}
if(textField == textFieldC) {
return newLength <= 8
}
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength = (textField.text ?? "").count + string.count - range.length
switch textField {
case textFieldA :
return newLength <= 6
case textFieldB:
return newLength <= 7
case textFieldC:
return newLength <= 8
default:
return true
}
}
您正在使用==将一个字段与多个字段进行比较,因此您应该可以像下面这样进行操作:
switch (textField) {
case textFieldA:
return newLength <= 6
case textFieldB:
return newLength <= 7
case textFieldC:
return newLength <= 8
default:
return true
}