skip to Main Content

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


  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)
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search