Json Swift
Json Swift

Reputation: 31

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

Upvotes: 0

Views: 421

Answers (2)

Sumit Jangra
Sumit Jangra

Reputation: 631

Create String extension to assign SubSequence to String property.

extension String {
    mutating func removeFirstChar() {
      self = String(self.dropFirst())
    } 
}

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

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())

Upvotes: 2

Related Questions