Here it is. It is a little bit verbose to make it easier to understand.
Don't forget to close the thread if that works. Otherwise, explain what is the problem. And do the same on your older threads to keep forum clean.
struct Squadre: Identifiable, Equatable { // ad hoc, for testing. Adapt to yours.
var id = UUID()
var squadra: String
var punti: Int
static func test() -> [Squadre] {
[Squadre(squadra: "One", punti: 1), Squadre(squadra: "Seven", punti: 7), Squadre(squadra: "Three", punti: 3), Squadre(squadra: "Nine", punti: 9), Squadre(squadra: "Twelve", punti: 12), Squadre(squadra: "Five", punti: 5), Squadre(squadra: "Four", punti: 4)]
}
}
struct ContentView: View {
@State private var squadre: [Squadre] = Squadre.test()
@State private var firstHalfSquadre: [Squadre] = []
@State private var secondHalfSquadre: [Squadre] = []
var body: some View {
HStack {
List {
ForEach($firstHalfSquadre, id: \.id) { $sq in // do not reuse squadre as name
HStack {
Text(sq.squadra)
Text("\(sq.punti)")
}
}
}
List {
ForEach($secondHalfSquadre, id: \.id) { $sq in // do not reuse squadre as name
HStack {
Text(sq.squadra)
Text("\(sq.punti)")
}
}
}
}
.onAppear {
let lastHalfCount = squadre.count / 2
let firstHalfCount = squadre.count - lastHalfCount // to take care if count is odd
firstHalfSquadre = squadre.sorted(by: { $0.punti > $1.punti } ) // decreasing order
firstHalfSquadre = firstHalfSquadre.dropLast(lastHalfCount) // remove last half
secondHalfSquadre = squadre.sorted(by: { $0.punti > $1.punti } ) // decreasing order
secondHalfSquadre = Array(secondHalfSquadre.dropFirst(firstHalfCount)) // keep last half
// dropFirst creates a subsequence, not an array… So need to convert to Array.
}
.onChange(of: squadre) {
let lastHalfCount = squadre.count / 2
let firstHalfCount = squadre.count - lastHalfCount
firstHalfSquadre = squadre.sorted(by: { $0.punti > $1.punti } ).dropLast(lastHalfCount)
secondHalfSquadre = Array(squadre.sorted(by: { $0.punti > $1.punti } ).dropFirst(firstHalfCount))
}
// To play with it…
Button(action: {
squadre.append(Squadre(squadra: "Two", punti: 2))
}) {
Text("Add Punti 2")
}
Button(action: {
squadre[0] = Squadre(squadra: "New One", punti: 10)
}) {
Text("Modify first \(squadre[0].squadra) to 10")
}
Button(action: {
let newValue = squadre[0].punti + 5
squadre[0] = Squadre(squadra: "New first", punti: newValue)
}) {
Text("Add 5 to first")
}
}
}