Search code examples
iosswiftoptional-values

Swift: Checking for the existence of a uitextfield


I have a controller that will have a variable number of textfields. On a button press I want to check for the existence of, whether or not its empty, and check the character count of the input.

I'm trying the following, which works fine if homePhone exists

if homePhone?.text != ""{
if countElements(homePhone1.text) != 10{
    validInput = false
    validationError = "Home Phone must be 10 digits"
}
}

But when a textfield does not exist (mobile) I get a fatal error

if mobilePhone?.text != ""{
if countElements(mobilePhone.text) != 10{
    validInput = false
    validationError = "Mobile Phone must be 10 digits"
}
}

fatal error: unexpectedly found nil while unwrapping an Optional value

Obviously I'm not doing the check correctly, optionals and unwrapping is continually tripping me up.


Solution

  • You can unwrap your textfield and check if it exists:

    if let mobilePhoneField = mobilePhone{
      if mobilePhoneField.text != ""{
        if countElements(mobilePhoneField.text) != 10{
            validInput = false
            validationError = "Mobile Phone must be 10 digits"
        }
      }
    }