TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Mapping firebase sub collections to custom structs

Forums > SwiftUI

I have a collection of teams in my Firebase Cloud Firestore each of which have players. I have previously saved each of these players in an array inside the team document however found this to be inefficient and slow the app dramatically. After some research I have converted this array into a sub collection called players and want to access it the same way.

Here is my team and player model (simplified):

struct DBTeam: Identifiable, Codable{
    @DocumentID var id: String?
    var name: String
    var colour: Int
    var dateCreated: Date
    var players: [DBPlayer] = [DBPlayer]()

    var userID: String?
}

struct DBPlayer: Identifiable, Equatable, Codable{
    var id: String = UUID().uuidString
    var name: String

    static func ==(lhs: DBPlayer, rhs: DBPlayer) -> Bool {
        return lhs.name == rhs.name && lhs.id == rhs.id
    }
}

I then use this repository to get all the data and feed it into my view model:

class TeamRepository: ObservableObject{

    var db = Firestore.firestore()

    @Published var teams = [DBTeam]()

    init(){
        loadData()
    }

    func loadData(){

        let userID = Auth.auth().currentUser?.uid

        db.collection("teams")
            .order(by: "name")
            .whereField("userID", isEqualTo: userID ?? "")
            .addSnapshotListener { (querySnapshot, error) in
            if let querySnapshot = querySnapshot{
                self.teams = querySnapshot.documents.compactMap { document in
                    do{
                        let x = try document.data(as: DBTeam.self)
                        return x
                    }
                    catch{
                        print(error)
                    }

                    return nil

                }
            }
        }
    }
}

I have tried running this code again to see if by any chance it would work, but it didn't. By using these new sub collections, is this the most efficient way to store a bunch of players to one team and then reference them? If not any other suggestions? And how would I access these sub collections and store them into the array of players found in the DBTeam struct?

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.