无法访问具有索引的数组的成员



我正在尝试用Firebase中的数据填充数组。但是在填充数组之后,我不能从其索引中调用其成员。我用这个函数填充数组

func loadSounds(){
Firestore.firestore().collection("data").getDocuments{ (snapshot, error) in
if error == nil{
for document in snapshot!.documents{
let name = document.data()["name"] as? String ?? "error"
let sounds = document.data()["sounds"] as? [String : [String : Any]]

var soundsArray = [dataSound]()
if let sounds = sounds{
for sound in sounds {
let soundName = sound.value["name"] as? String ?? "error"
let soundImage = sound.value["image"] as? String ?? "error"
soundsArray.append(dataSound(name: soundName , image: soundImage ))
}
}

categoriesArray.append(Category(category: name , sounds: soundsArray))
}
print(categoriesArray[0].category)

} else {
print(error)
}
} }

当我尝试从视图访问它时,它会给出索引越界错误。

struct ContentView: View {
init(){
loadSounds()
}
var body: some View {
Text(categoriesArray[0].category)}}

如果我试图通过ForEach访问它,它是有效的,当我试图从loadSounds功能打印它时,它也是有效的,但我需要从View中的索引访问它们。谢谢你的帮助。

永远不要在SwiftUI视图的渲染区域中通过索引访问数组的项,在几乎所有情况下,第一次渲染视图时数组都是空的。

在您的情况下,使用.first并处理可选的

var body: some View {
Text(categoriesArray.first?.category ?? "No value")}} // or empty string

最新更新