I have two entities in my project, DBTeam and DBPlayer. DBTeam has a one to many relationship with DBPlayer allowing multiple players to be associated with one team; DBPlayer then has an attribute called name which is what I want to base the alphabetical order off of. What's the easiest way to list these alphabetically off of name?
Here is the code I am using to list them at the moment. I have tried .sorted
but that just produced other errors.
struct PlayersView: View{
var team: DBTeam
var body: some View{
NavigationView{
List{
ForEach(Array(team.player as? Set<DBPlayer> ?? []), id: \.id){ player in //I want to sort this ForEach here
Text(player.name ?? "Player Name")
}
}
.navigationBarTitle("Players")
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
Try using localizedCaseInsensitiveCompare
:
List {
let array = Array(team.player as? Set<DBPlayer> ?? [])
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
ForEach(array, id: \.id) { player in
Text(player.name ?? "Player Name")
}
}