我有一個應用程式,用戶可以在其中對他們看過的電影進行評分,我希望能夠將它們放入tableView. 評級存盤在 Firestore 中,我想將KEY和 value 都放入 aStruct中,以便可以訪問tableView.
但是,我看到的任何站點/教程/堆疊問題都只能獲取 Maps 值,而不是鍵(在本例中為標題名稱)。我可以訪問該值,但只能使用欄位鍵,但這就是我想要獲得的(參見嘗試 1)

結構:
struct Rating: Codable {
var ratedTitle: String
var ratedRating: Int
}
多變的:
var ratedList = [Rating]()
加載資料功能(嘗試1):
let dbRef = db.collection("Users").document(userID)
dbRef.getDocument { document, error in
if let error = error {
print("There was an error \(error.localizedDescription)")
} else {
if let docData = document!.data() {
let titleRating = docData["Title Ratings"] as? [String: Int]
let midnightMass = titleRating!["Midnight Mass"]
print("Rating given to Midnight Mass: \(midnightMass!) stars")
}
}
}
//Prints: Rating given to Midnight Mass: 2 stars
也嘗試過(但我不知道如何將此陣列放入 tableView 并將第一個索引作為標題標簽,第二個索引作為陣列中每部電影的評級標簽)嘗試 2:
if let docData = document!.data() {
let titleRating = docData["Title Ratings"] as? [String: Int]
self.userRatedList = titleRating!
print("userRatedList: \(self.userRatedList)")
}
//Prints: userRatedList: ["Midnight Mass": 2, "Bly Manor": 5]
嘗試 3:
if let docData = document!.data() {
let titleRating = docData["Title Ratings"] as? [String: Int]
self.ratedList = [Rating(ratedTitle: <#T##String#>, ratedRating: <#T##Int#>)]
//Don't know what I would put as the ratedTitle String or ratedRating Int.
self.ratedList = [Rating(ratedTitle: titleRating!.keys, ratedRating: titleRating!.values)]
//Cannot convert value of type 'Dictionary<String, Int>.Keys' to expected argument type 'String'
//Cannot convert value of type 'Dictionary<String, Int>.Values' to expected argument type 'Int'
}
uj5u.com熱心網友回復:
首先,我不確定為什么需要結構符合 Codable?
現在,根據我所看到的,“Title Ratings”是一個帶有 String 鍵和 Int 值的字典。你把這個復雜化了。如果要單獨訪問每個元素的鍵和值,請使用 for-in 回圈。
//Declare your global variable
var ratedList = [Rating]()
//If you are using an if let, there is not need to force unwrap
if let docData = document.data() {
if let userRatingList = docData["Title Ratings"] as? [String: Int] {
for (key, value) in userRatingList {
let rating = Rating(ratedTitle: key, ratedRating: value)
ratedList.append(rating)
}
//reload your tableView on the main thread
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452930.html
上一篇:ForEach中的專案相互迭代
下一篇:在SwiftUI中從側面影片視圖
