我有几个文本字段,每个文本字段具有不同数量的最大字符。如何将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
        }
}

10-08 05:46