NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

ForEach with Array binding crash on item deletion

Forums > SwiftUI

Hi, can someone tell me why this code crashes when a token is deleted (amount reaches 0) from the array? And a possible workaround... Thanks!

I think the problem is with array.count which is not updated after index deletion and it goes out of range.

PS: This is the same problem of a previous post of mine but simplified and self contained.

import SwiftUI

class Player: ObservableObject {
    var name: String
    @Published var tokens: [Token] = [
        Token(name: "Goblin", amount: 3),
        Token(name: "Spirit", amount: 3),
        Token(name: "Beast", amount: 3)
    ]
    init(name: String) {
        self.name = name
    }
}

struct Token: Identifiable {
    let id = UUID()
    var name: String
    var amount: Int
}

struct ForEachView: View {
    @StateObject var player: Player
    var body: some View {
        VStack {
            List {
                ForEach(player.tokens.indices, id: \.self) { index in
                    TokenView(player: player, token: $player.tokens[index])
                }
            }
            Button("Delete first") {
                if !player.tokens.isEmpty {
                    player.tokens.remove(at: 0)
                }
            }
        }
    }
}

struct TokenView: View {
    @ObservedObject var player: Player
    @Binding var token: Token
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text("Name: \(token.name)")
                Text("Amount: \(token.amount)")
            }
            Spacer()
            Button("Decrease") {
                if token.amount > 1 {
                    token.amount -= 1
                } else {
                    let index = player.tokens.firstIndex { item in
                        item.id == token.id
                    }
                    if let index = index {
                        player.tokens.remove(at: index)
                    }
                }
            }
        }
    }
}

struct ForEachView_Previews: PreviewProvider {
    static var previews: some View {
        ForEachView(player: Player(name: "Player"))
    }
}

   

Here is a possible solution I found, but Token must be implemented as an ObservableObject and not as a struct:

import SwiftUI

class Player: ObservableObject {
    var name: String
    @Published var tokens: [Token] = [
        Token(name: "Goblin", amount: 3),
        Token(name: "Spirit", amount: 3),
        Token(name: "Beast", amount: 3),
        Token(name: "Angel", amount: 3),
        Token(name: "Demon", amount: 3),
        Token(name: "Bird", amount: 3),
        Token(name: "Dragon", amount: 3)
    ]
    init(name: String) {
        self.name = name
    }
}

class Token: Identifiable, ObservableObject {
    let id = UUID()
    let name: String
    @Published var amount: Int
    init(name: String, amount: Int) {
        self.name = name
        self.amount = amount
    }
}

struct ForEachView: View {
    @StateObject var player: Player
    var body: some View {
        VStack {
            List {
                ForEach(player.tokens) { token in
                    TokenView(player: player, token: token)
                }
            }
            Button("Delete first") {
                if !player.tokens.isEmpty {
                    player.tokens.remove(at: 0)
                }
            }
        }
    }
}

struct TokenView: View {
    @ObservedObject var player: Player
    @ObservedObject var token: Token
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text("Name: \(token.name)")
                Text("Amount: \(token.amount)")
            }
            Spacer()
            Button("Decrease") {
                if token.amount > 1 {
                    token.amount -= 1
                } else {
                    let index = player.tokens.firstIndex { item in
                        item.id == token.id
                    }
                    if let index = index {
                        player.tokens.remove(at: index)
                    }
                }
            }
        }
    }
}

struct ForEachView_Previews: PreviewProvider {
    static var previews: some View {
        ForEachView(player: Player(name: "Player"))
    }
}

   

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

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.