gpt4 book ai didi

swift - 全局变量似乎失去了值(value)( swift )

转载 作者:行者123 更新时间:2023-11-30 12:19:24 25 4
gpt4 key购买 nike

这是我从 firebase 中提取数据的代码。
listofnames(双维)和names(单维)是String类型的全局数组。

但是,当我打印 listofnames 时,输出窗口中会显示一个空数组,而如果我注释第一行 (self.listofnames = [[]]),代码就会正常运行。

我已将引用链接到 Firebase 数据库

请帮忙。

var databasehandle:FIRDatabaseHandle?

let time = ["8AM - 9AM", "9AM - 10AM","10AM - 11AM", "11AM -12PM", "12PM - 1PM","1PM - 1:30PM","2PM - 3PM","3PM - 4PM","4PM - 5PM","5PM - 6PM","6PM - 7PM","7PM - 7:30PM"]

var ref:FIRDatabaseReference!
var day: String = "Monday"
var users :String = "First years"

func loaddata()
{
self.listofnames = [[]]
for x in 0...((time.count)-1)
{
ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
if let namesfromFirebase = snapshot.value as? [String:Any]
{
let y = namesfromFirebase.count
for i in 1...y
{
self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
}
}
self.listofnames.append(self.names)
self.names = []
})
}
print(self.listofnames)
self.tableView.reloadData()
}

最佳答案

observeSingleEvent 异步工作,稍后调用闭包。

有一个简单的解决方案:将两行移入闭包中:

func loaddata()
{
self.listofnames = [[]]
for x in 0..<time.count // no parentheses and math needed when using `..<`
{
ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
if let namesfromFirebase = snapshot.value as? [String:Any]
{
let y = namesfromFirebase.count
for i in 1...y
{
self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
}
}
self.listofnames.append(self.names)
self.names = []
print(self.listofnames)
self.tableView.reloadData()
})
}
}

关于swift - 全局变量似乎失去了值(value)( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44983969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com