[英]How to make ForEach loop for a Codable Swift Struct's Dictionary (based on Firestore map)
我正在嘗試做一個 ForEach 循環,列出用戶可能擁有的所有社交媒體。 這將在一個可滾動的列表上,相當於音樂流媒體應用程序有一個列表,列出了您保存在庫中的所有歌曲。 用戶的社交媒體列表實際上是一本字典。
我的 MainViewModel class 實現了 Firebase 的所有功能。 見下文。
class MainViewModel: ObservableObject {
@Published var errorMessage = ""
@Published var user: User?
init() {
DispatchQueue.main.async {
self.isUserCurrentlyLoggedOut = FirebaseManager.shared.auth.currentUser?.uid == nil
}
readCodableUserWithMap()
}
@Published var isUserCurrentlyLoggedOut = false
func handleSignOut() {
isUserCurrentlyLoggedOut.toggle()
try? FirebaseManager.shared.auth.signOut()
}
func readCodableUserWithMap() {
guard let uid = FirebaseManager.shared.auth.currentUser?.uid else {
self.errorMessage = "Could not find firebase uid"
print("FAILED TO FIND UID")
return
}
let userID = uid
let docRef = FirebaseManager.shared.firestore.collection("users").document(userID)
docRef.getDocument { (document, error) in
if let err = error {
print(err.localizedDescription)
return
}
if let doc = document {
let user = try! doc.data(as: User.self)
if let mappedField = user.socials {
mappedField.forEach { print($0.key, $0.value) }
}
}
}
}
}
readCodableUserWithMap()應該初始化我的可編碼結構,它代表一個用戶。 見下文。
struct User: Identifiable, Codable {
@DocumentID var id: String?
var socials: [String: String]?
var uid, email, name, bio, profileImageUrl: String?
var numSocials, followers, following: Int?
}
手頭的問題:在我的儀表板視圖中,我試圖列出用戶可以擁有的所有社交媒體。 我無法為我的用戶創建 ForEach 循環。
我願意:
ForEach(vm.user?.socials.sorted(by: >), id: \.key) { key, value in
linkDisplay(social: key, handler: value)
.listRowSeparator(.hidden)
}.onDelete(perform: delete)
這給了我以下錯誤:
可選類型“[Dictionary<String, String>.Element] 的值?” (又名“Optional<Array<(key: String, value: String)>>”)必須解包為類型為“[Dictionary<String, String>.Element]”的值(又名“Array<(key: String,值:字符串)>')
可選類型“[String: String]?”的值? 必須解包以引用包裝基類型“[String: String]”的成員“sorted”
我試過合並使用?? 但這不起作用,盡管我認為我做錯了什么。 強制展開是我嘗試過的方法,但是當它是一個空字典時它使應用程序崩潰。
為了以防萬一,這里是數據庫層次結構: firebase hierarchy
TLDR:我如何制作一個 ForEach 循環來列出我所有用戶的媒體?
您將vm.user
和socials
都作為可選項。 ForEach
循環需要非可選值,因此您可以嘗試使用以下方法為ForEach
循環解包這些選項。
if let user = vm.user, let socials = user.socials {
ForEach(socials.sorted(by: > ), id: \.key) { key, value in
linkDisplay(social: key, handler: value)
.listRowSeparator(.hidden)
}.onDelete(perform: delete)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.