skip to Main Content

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?’

2

Answers


  1. 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())
    
    Login or Signup to reply.
  2. Create String extension to assign SubSequence to String property.

    extension String {
        mutating func removeFirstChar() {
          self = String(self.dropFirst())
        } 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search