UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

3      

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

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

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.