palumbes
palumbes

Reputation: 39

How to store input from TextField into an array of Strings in Swift?

I have a Textfield and a button. Wenn the button is pressed, a function is triggered that stores the items that are typed in the TextField into an Array and then outputs the current contents of the Array to the console. How to store the input from the TextField into an array of strings? I've just started learning Swift and need your help. Thanks a lot in advance!

 @IBOutlet weak var inputEntered: UITextField!


@IBAction func buttonAddToList(_ sender: UIButton) {

    var shoppingList: [String] = []

    let item = inputEntered.text
    shoppingList.append(item)

    for product in shoppingList {
        print(product)
    }

}

Upvotes: 2

Views: 3786

Answers (1)

Joshua
Joshua

Reputation: 2451

If you want to store all inputs declare your strings outside the function

@IBOutlet weak var inputEntered: UITextField!
var shoppingList: [String] = [] // our holder of strings

@IBAction func buttonAddToList(_ sender: UIButton) {

    if let item = inputEntered.text, item.isEmpty == false { // need to make sure we have something here
        shoppingList.append(item) // store it in our data holder
    }
    inputEntered.text = nil // clean the textfield input

    for product in shoppingList {
        print(product) // prints the items currently in the list
    }
}

The flow will be, everytime you click the button it adds that to the list and remove the text input value so it feels like you are ready for the next input/item in the list.

Upvotes: 1

Related Questions