GO FURTHER, FASTER: Try the Swift Career Accelerator 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)
        }

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      

Hacking with Swift is sponsored by RevenueCat.

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

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.