Swift数组存储数据问题:Firebase分类数据存储咨询
Hey there! Let's walk through how to query Firebase for your target genres and organize the returned data properly. Here's a step-by-step breakdown tailored to your needs:
First, we'll set up our genre list and initialize empty arrays to hold data for each category. This keeps your data organized right from the start:
// List of genres we want to fetch from Firebase var genresLabelIndex : [String] = ["Horror", "Fiction", "Romance"] // Empty arrays to store data for each genre (matches your InformationForFeed type) var horrorData = [InformationForFeed]() var fictionData = [InformationForFeed]() var romanceData = [InformationForFeed]()
Next, we'll query Firebase (using Firestore as the common example here) to pull documents matching our genres, then sort each entry into its corresponding array. We'll also handle error cases to keep things robust:
import FirebaseFirestore let db = Firestore.firestore() // Query all documents where the "genre" field is in our target list db.collection("your-feed-collection-name") .whereField("genre", in: genresLabelIndex) .getDocuments { snapshot, error in // Handle query errors first if let error = error { print("Failed to fetch data: \(error.localizedDescription)") return } guard let documents = snapshot?.documents else { print("No matching documents found") return } // Loop through each document and sort into the right genre array for document in documents { // Parse the document into your InformationForFeed model do { let feedItem = try document.data(as: InformationForFeed.self) // Route the item to its corresponding array switch feedItem.genre { case "Horror": horrorData.append(feedItem) case "Fiction": fictionData.append(feedItem) case "Romance": romanceData.append(feedItem) default: print("Skipping item with unknown genre: \(feedItem.genre ?? "Unspecified")") } } catch { print("Failed to parse document \(document.documentID): \(error)") } } // At this point, your genre arrays are populated and ready for use (e.g., updating UI) print("Genre data loaded successfully!") }
InformationForFeed Model Definition For context, here's a typical Codable-compliant definition for your InformationForFeed struct (works seamlessly with Firestore's data parsing):
struct InformationForFeed: Codable { var id: String? var genre: String? var title: String? var description: String? // Add any other fields your feed items require // Optional: Define coding keys if your Firestore field names differ from struct properties enum CodingKeys: String, CodingKey { case id case genre case title case description } }
If you anticipate adding more genres later, use a dictionary instead of individual arrays to avoid repetitive code. Here's how that would look:
// Initialize a dictionary to map genres to their data arrays var genreDataDict: [String: [InformationForFeed]] = [:] // Populate the dictionary with empty arrays for each genre for genre in genresLabelIndex { genreDataDict[genre] = [] } // Then, in your query completion handler, replace the switch statement with: if let genre = feedItem.genre { genreDataDict[genre]?.append(feedItem) }
This way, you won't need to create a new variable every time you add a genre—just update the genresLabelIndex array!
内容的提问来源于stack exchange,提问作者AndrewS

