Search code examples
swiftuitextfieldis-emptyswift-array

How not to append item from UITextField to array if empty or blank spaces - Swift


This is my very first question on Stack Overflow so I hope I'm following the rules correctly.

I'm making a To-Do list app in Swift and I'm trying to prevent blank or empty spaces from being appended to the table.

My UITextField:

@IBOutlet weak var item: UITextField!

My addItem button:

@IBAction func addItem(sender: AnyObject) {

    if item.text.isEmpty {
    //Do not append item to array
}

Thank you for any help!


Solution

  • You can do this

    if item.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) != "" {
        //addNew()
    }
    

    stringByTrimmingCharactersInSet : Returns a new string made by removing from both ends of the receiver characters contained in a given character set. The parameter NSCharacterSet.whitespaceCharacterSet removes the whitespace from both ends.