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

SOLVED: SwiftUI by Example Arrays/List - 3 x Full English

Forums > Books

I'm trying to make the final app Order resemble a bill

Instead of having multiple rows with the same item, i'm trying to group items:

3 x Full English 2 x Coke 1 x Stake

but the following code runs into issues:

func add(item: MenuItem) {

        let index = (items.firstIndex(of: item))

        if  (index == nil) {
            print("could not find first item")

            items.append(item)

        } else if (index) != nil {
            print("found first item")
            items[index!].qty += 1
        }
    }

to make the code above work you'll need to add a qty field to MenuItems. The code above works for a new item and incrementing that item but then unexplainably adds a new item. If you have a more alegant solutions please enlighten me?

struct MenuItem: Codable, Equatable, Identifiable {
    var id: UUID
    var name: String
    var photoCredit: String
    var price: Int
    var restrictions: [String]
    var description: String
    var qty: Int = 1

Thank you very much, with your help I managed to get everything working.

    let index = items.firstIndex(where: {$0.id == item.id})

        if (index != nil) {
            items[index!].qty += 1
        } else {
            items.append(item)
        }

3      

try a guard let statement and use .firstIndex(where

func add(item: MenuItem) {
guard let index = items.firstIndex(where: { $0 == item }) else {
print("Could not find first item")
items.append(item)
return
}
print("First item found")
items[index].qty += 1
}

Not more elegant but a lot safer and you dont have to force unwrap anything

4      

I tried your code in playground and it seems to be working ok with how i set it up. How have you got your MenuItems struct set up?

4      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.