title: UITextField setting maximum character length in Swift
body: <p>How can I override this UITextField function so that it will have a limit on the maximum number of characters?</p>
  
  <pre><code>override func shouldChangeText(in range: UITextRange, replacementText text: String) -&gt; Bool {
  
  }
  </code></pre>
  
  <p>I've done some research on stack, but all I can find is this function (see below). First off, I can't see how this can be an override, and second, it's using NSRange as a parameter where I have UITextRange. How can this be implemented? thanks</p>
  
  <pre><code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, 
                  replacementString string: String) -&gt; Bool {
          let currentString: NSString = textField.text! as NSString
          let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
          return newString.length &lt;= 4
      }
  </code></pre>
  
  <p>My failed try:</p>
  
  <pre><code>override func shouldChangeText(in range: UITextRange, replacementText text: String) -&gt; Bool {
          let currentString: NSString = self.text! as NSString
          let newString: NSString = currentString.replacingCharacters(in: range, with: text) as NSString
          return newString.length &lt;= 4
      }
  </code></pre>
  
  <p>error: Cannot convert value of type 'UITextRange' to expected argument type 'NSRange' (aka '_NSRange')</p>