Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Deleting last row in ForEach

Tags:

ios

swiftui

I am trying to remove rows inside a ForEach. Removing the last row always throws an index out of range exception. Removing any other row does not.

ForEach(Array(player.scores.enumerated()), id: \.element) { index, score in
    HStack {
        if self.isEditSelected {
            Button(action: {
                self.player.scores.remove(at: index)
            }, label: {
                Image("delete")
            })
        }        
        TextField("\(score)", value: self.$player.scores[index], formatter: NumberFormatter())
    }
}

I have tried using ForEach(player.indices...) & ForEach(player.scores...), but see the same problem.

Looks to me like the crash happens here self.$player.scores[index], as hardcoding the index to any value other that the last row is working.

Does anyone know how to fix this? Or if there is a better approach.

like image 400
aneurinc Avatar asked Apr 25 '20 23:04

aneurinc


2 Answers

Here is fix

ForEach(Array(player.scores.enumerated()), id: \.element) { index, score in
    HStack {
        if self.isEditSelected {
            Button(action: {
                self.player.scores.remove(at: index)
            }, label: {
                Image("delete")
            })
        }        
        TextField("\(score)", value: Binding(   // << use proxy binding !!
            get: { self.player.scores[index] },
            set: { self.player.scores[index] = $0 }), 
            formatter: NumberFormatter())
    }
}

backup

like image 168
Asperi Avatar answered Sep 30 '22 08:09

Asperi


Based on @Asperi answer

public extension Binding where Value: Equatable {
    static func proxy(_ source: Binding<Value>) -> Binding<Value> {
            self.init(
                get: { source.wrappedValue },
                set: { source.wrappedValue = $0 }
            )
    }
}

You can use this as follows:

TextField("Name", text: .proxy($variable))
like image 30
AlbertUI Avatar answered Sep 30 '22 08:09

AlbertUI