jojiReptiloid
jojiReptiloid

Reputation: 286

maxLength for switch text field

I have several text fields, each with a different number of maximum characters. How can I change the if branch to enum and use 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
    }

Upvotes: 1

Views: 77

Answers (2)

Ankur Lahiry
Ankur Lahiry

Reputation: 2315

 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 
        }
}

Upvotes: 3

Scriptable
Scriptable

Reputation: 19758

You are comparing one field to multiple fields using == so you should be able to just do it like below:

switch (textField) {
   case textFieldA:
       return newLength <= 6
   case textFieldB:
       return newLength <= 7
   case textFieldC:
       return newLength <= 8
   default:
       return true
}

Upvotes: 2

Related Questions