GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.