I\'m learning how to utilize table views & table view cells and today I wanted to practice using sections within table views. Setting the section title and sorting the d
This a simple implementation of your problem. You have a player class which is your Firebase data.
class Player {
var name: String
var teamName: String
init(name: String, teamName: String) {
self.name = name
self.teamName = teamName
}
}
Create a Team
class to store your section data.
class Team {
var teamName: String
var players: [Player]
init(teamName: String, players: [Player]) {
self.teamName = teamName
self.players = players
}
}
Store all the players in an array players
after you get the data from Firebase. Now you can have a method which returns an array which contains Team
objects which has teamName
and players
which is an array containing the filtered players of the sharing the same teamName
func getTeams() -> [Team] {
var teams: [Team] = []
while !players.isEmpty {
guard let referencePlayer = players.first else {
print("All players sorted.")
return []
}
let filteredPlayers = players.filter { (player) -> Bool in
return player.teamName == referencePlayer.teamName
}
players.removeAll { (player) -> Bool in
return player.teamName == referencePlayer.teamName
}
let team = Team(teamName: referencePlayer.teamName, players: filteredPlayers)
teams.append(team)
}
return teams
}
Now call this method in viewDidLoad
and reload the table.
func numberOfSections(in tableView: UITableView) -> Int {
return teams.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return teams[section].players.count
}