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

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

1      

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

2      

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?

2      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.