How do I disable the user from typing two consecutive spaces in a UITextField?

The code I tried using is as follows:

```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let myString = myUITextField.text

    let regex = try? NSRegularExpression(pattern: " +", options: .caseInsensitive)
    let trimmedString: String? = regex?.stringByReplacingMatches(in: myString!, options: [], range: NSRange(location: 0, length: (myString?.characters.count)!), withTemplate: " ")

    myUITextField.text = trimmedString

    let maxLegnth = 40
    let currentString: NSString = textField.text! as NSString
    let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString

    return newString.length <= maxLegnth
}

```

PS: The rest of the code forces the user to type in 40 characters only. This is another requirement.