WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Consolidation 3: Create ShoppingList App got logic error on create new item (with section) -> it was duplicated

Forums > 100 Days of Swift

As title, I think the error was below. Any advise would be appreciated.

@objc func addItem(){
        let ac = UIAlertController(title: "Add Item", message: nil, preferredStyle: .alert)
        ac.addTextField { (tf) in
            tf.placeholder = "List name"
        }
        ac.addTextField { (tf) in
            tf.placeholder = "Item"
        }
        ac.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action) in
            let listName = ac.textFields?[0].text ?? "Shopping"
            let name = ac.textFields?[1].text ?? "Item"

            if self.shoppingLists.isEmpty{
                let item = Item(name: name, doneStatus: false)
                let list = ShoppingList(listName: listName, items: [item])
                self.shoppingLists.insert(list, at: 0)

            }else{
                for  (i, var list) in self.shoppingLists.enumerated(){
                    if list.listName.lowercased() == listName.lowercased(){

                        self.shoppingLists.remove(at: i)

                        let item = Item(name: name, doneStatus: false)
                        list.items.append(item)
                        self.shoppingLists.insert(list, at: i)

                    }else{
                        let item = Item(name: name, doneStatus: false)
                        let list = ShoppingList(listName: listName, items: [item])
                        self.shoppingLists.insert(list, at: 0)

                    }
                }

            }

            self.tableView.reloadData()
//            let indexPath = IndexPath(row: 0, section: 0)
//            self.tableView.insertRows(at: [indexPath], with: .automatic)
        }))
        present(ac, animated: true, completion: nil)
    }

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.