I have several different models, and would like to create a method in my view model to pass in any struct and query Firebase using the parameters passed into the method. My code is incorrect, but I am trying to figure out how to: 1) write logic to tell the function which @Published variable I would like it to access, 2) allow the method to use any of my model structs which all conform to codable by passing the struct name as an argument into the method and return a type of that struct. Here's the code I have written.
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift
import SwiftUI
import simd
class ShowDataViewModel: ObservableObject {
@Published var modelOneData = [modelOne]()
@Published var modelTwoData = [modelTwo]()
private var db = Firestore.firestore()
func getFromFirebase<T: Codable, X: Published>(collectionName: String, structToGetData: T, inputPublishedVar: X) {
db.collection(collectionName).addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("Nothing")
return
}
self.inputPublishedVar = documents.compactMap { QueryDocumentSnapshot -> T? in
return try? QueryDocumentSnapshot.data(as: structToGetData.self)
}
}
}
}