2

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)
    }

}
6
  • 1
    Please post code that you have tried - you'll not get replies from people on Stack Overflow unless you show you have had a go at it yourself and where you get stuck. Commented May 14, 2020 at 23:29
  • please post your code that you tried ? Commented May 14, 2020 at 23:35
  • I've just edited the post. Commented May 14, 2020 at 23:55
  • you need to declare your array as a property of your view controller. Move var shoppingList: [String] = [] out of your method buttonAddToList Commented May 15, 2020 at 0:05
  • You need also to force unwrap the text property let item = inputEntered.text! Commented May 15, 2020 at 0:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! It was very helpful. Do you know which methods could delete duplicates from the console? For loop generates duplicates that I don't need.
Update: To avoid duplicates generated by the for loop I wrote just print(shoppingList.last!) instead of for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.