0

I am trying to display a list of items on a shopping list. These items are added from two text fields (description and quantity). For some reason, I am not able to get the array to keep the previous items, instead, the previous items in the array disappear and the only item that shows was the most recent item entered. Can someone help me understand where I have gone wrong? Here is the code I have:

    @IBAction func add(_ sender: UIButton) {

    
    var shoppingList = [String]()
    
    if let x = descriptionField.text{
        if let y = quantityField.text{
            if x != "" && y != "" {
                if isStringAnInt(string: y){
                    shoppingList.append("\(y) x \(x)")
                }else{
                    [...]

2 Answers 2

1

Your shopping list array is set as empty every time in button action. you need the declare the array outside the button action.

var shoppingList = [String]()
@IBAction func add(_ sender: UIButton)
Sign up to request clarification or add additional context in comments.

Comments

0

You are declaring the array inside the function so as soon as you press the items add button it resets the previous array and that is the reason your item disappears. Declare your array outside the function and then use it inside the function. This will solve your issue.

1 Comment

How does this add anything to the answer provided yesterday?

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.