NEW: Learn SwiftData for free with my all-new book! >>

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


        } 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: {$ ==})

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


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")
print("First item found")
items[index].qty += 1

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


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?


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try 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.