NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until October 1st.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.