UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.