Adding space between textfield character when typing in text filed
<p>I have a <code>textfield</code> with maximum character range 16, After every 4 characters, I want to add minus character or space and then writing The rest of the characters like this sample 5022-2222-2222-2222. 
there is my code but that's don't work, how can do this?</p>

<pre><code>if textField.text?.characters.count  == 5 {

               let  l = textField.text?.characters.count
            let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
            attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
            cartNumberTextField.attributedText = attributedString

            }

            else if textField.text?.characters.count  == 9 {

                let  l = textField.text?.characters.count
                let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
                attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
                cartNumberTextField.attributedText = attributedString

            }

            else if textField.text?.characters.count  == 13 {

                let  l = textField.text?.characters.count
                let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
                attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
                cartNumberTextField.attributedText = attributedString

            }
</code></pre>

<p>I am adding this code in <code>UITextField</code> <code>shouldChangeCharactersIn</code> range method.</p>