Make sure if the textbox from the UITextFields collection is empty

I currently have a collection of UITextFields hooked up from IB to my Swift code. The user has the option to click a button to go to the next view, but my application requires all fields to be filled. Below is my method that checks if the textbox 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 or what to return if none of them are empty. The caller checks the return value and performs an action depending on whether it returns a field or not. I am vaguely aware that Swift's Optionals feature can help with this, but I'm not sure how.

What do I need to return fn so that the caller knows that none of the fields from the collection are empty?

+3


source to share


1 answer


You set it up fine - since you are already returning an optional UITextField?

, if there are no empty text fields return nil

:

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

      



When called, note that you will get the additional value back. Unbind it with an optional binding:

if let emptyField = findEmptyField() {
    // focus emptyField or give a message
} else {
    // all fields filled, ok to continue
}

      

+1


source







All Articles