3

I currently have a collection of UITextFields wired from IB to my Swift code. The user has option to tap a button to proceed to the next view, but my app requires all fields to be filled. Below is my method that checks if a text field is empty:

func findEmptyField() -> UITextField? {
        for field in fieldsCollection {
            if field.text.isEmpty {
                return field
            }
        }
        //Return here a value signifying that no fields are empty.
    }

This method is only partially implemented, as I'm not sure how & what to return if none of them are empty. The caller of this function checks the return value and performs an action dependent on whether it returns a field or not. I vaguely understand that the optionals feature of Swift can help with this, but I'm not certain how.

What should I make the fn return so that the caller recognizes that none of the fields from the collection are empty?

Satre
  • 1,724
  • 2
  • 18
  • 22

1 Answers1

1

You've set it up perfectly -- since you're already returning an optional UITextField?, if there aren't any empty text fields, return nil:

func findEmptyField() -> UITextField? {
    for field in fieldsCollection {
        if field.text.isEmpty {
            return field
        }
    }
    return nil
}

When calling it, note that you'll get an optional value back. Unwrap it with optional binding:

if let emptyField = findEmptyField() {
    // focus emptyField or give a message
} else {
    // all fields filled, ok to continue
}
Nate Cook
  • 92,417
  • 32
  • 217
  • 178