作者:拍友2702932701 | 来源:互联网 | 2023-09-25 05:19
IhaveaFirebasedatabasethatismodeledassuch:我有一个这样建模的Firebase数据库::users:some-random
I have a Firebase database that is modeled as such:
我有一个这样建模的Firebase数据库:
: users
: some-random-id-1
- username:"user1"
- email:"email1@gmail.com"
: some-random-id-2
- username:"user2"
- email:"email2@gmail.com"
I am trying to iterate through all the users in the dictionary of data and append the username into a list in the file to be used for other purposes. I created a string array (userslist) variable and in viewdidload(), I wrote the following code below:
我尝试遍历数据字典中的所有用户,并将用户名附加到文件中的列表中,以便用于其他目的。我创建了一个字符串数组(userslist)变量,在viewdidload()中,我编写了以下代码:
ref = Database.database().reference()
ref?.observe(.value, with: { (snapshot) in
let dataDict = snapshot.value as! NSDictionary
let x = dataDict["users"] as! NSDictionary
print(x)
print("--------")
for user in x{
let y = user.value as? [String: String]
let z = y!["username"]
print(z)
self.userslist.append(z!)
print(self.userslist)
print("NEXT")
}
})
print(self.userslist)
Inside the brackets of the snapshot, when I print self.userslist, I can see that each element is getting added, but when I print it a final time outside of the brackets, it shows it as an empty array. I think that the elements are only appended in the scope of those brackets so I cant access the filled array anywhere else. How do I get around this so I can use the data I appended?
在快照的括号内,打印self。userslist,我可以看到每个元素都被添加了,但是当我最后一次在括号外打印时,它显示为一个空数组。我认为这些元素只添加在括号的范围内,所以我无法访问填充数组。如何绕过这个,以便使用我添加的数据?
1 个解决方案