You could build a new array
@State private var halfSquadre: [Squadre] = []
Then at some point (for instance .onAppear), initialise it
halfSquadre = squadre.sorted(by: { $0.punti < $1.punti } ) // increasing order
let halfCount = squadre.count / 2 // take care if count is uneven : if 11, do you want to display 5 or 6 ?
halfSquadre = halfSquadre.dropLast(halfCount) // remove last half
Use it in ForEach:
List {
ForEach(halfSquadre) { squadre in
HStack {
Text(squadre.squadra)
Text("\(squadre.punti)")
}
}
}
If you want to update dynamically, use onChange. Note that I created a Squadre struct for the test.
struct Squadre: Identifiable, Equatable {
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 halfSquadre: [Squadre] = []
var body: some View {
VStack {
List {
ForEach($halfSquadre, id: \.id) { $sq in // do not reuse squadre as name
HStack {
Text(sq.squadra)
Text("\(sq.punti)")
}
}
}
.onAppear {
halfSquadre = squadre.sorted(by: { $0.punti < $1.punti } ) // increasing order
let halfCount = squadre.count / 2 // take care if count is uneven : if 11, do you want to display 5 or 6 ?
halfSquadre = halfSquadre.dropLast(halfCount) // remove last half
}
.onChange(of: squadre) {
halfSquadre = squadre.sorted(by: { $0.punti < $1.punti } ).dropLast(squadre.count / 2)
}
Button(action: {
squadre.append(Squadre(squadra: "Two", punti: 2))
}) {
Text("Add Punti 2")
}
Button(action: {
squadre[0] = Squadre(squadra: "Ten", punti: 10)
}) {
Text("Modify first to 10")
}
}
}
}