简体   繁体   中英

Check if if a text field from a collection of UITextFields is empty

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM