Search code examples
iosswiftstringuitextfield

How to remove first character from textfield value?


If my textfield takes 11 characters and I need to remove first character and then pass it as a parameter. I tried this code:

var dropFirst: String?
if emailPhoneTextField.text?.count == 11 {
    dropFirst = emailPhoneTextField.text?.dropFirst()
    emailPhoneTextField.text = dropFirst 
}

I receive this error:

Cannot assign value of type 'String.SubSequence?' (aka 'Optional') to type 'String?'


Solution

  • dropFirst returns SubSequence so you can't assign it directly to textfield's text property that accepts an optional string (String?) , So replace

    dropFirst = emailPhoneTextField.text?.dropFirst()
    

    With

    dropFirst = String(emailPhoneTextField.text!.dropFirst())