问题描述
我将数据存储在Firebase中,并且找到了一种创建仅包含键的数组的方法。第一个打印语句正确打印出数组。但是,在数据库引用之外,变量listOfBannedNames
似乎没有保存数组。数组以[]的形式打印出来,里面没有任何键。我想将数组存储在变量listOfBannedNames中,以备后用。
let username = username
let formattedUsername = formatUsername(username: username)
var listOfBannedNames = [String]()
ref.observeSingleEvent(of: .value,with: {
snapshot in
var bannedNamesList = [String]()
for bannedNames in snapshot.children {
bannedNamesList.append((bannedNames as AnyObject).key)
}
listOfBannedNames = bannedNamesList
print(listOfBannedNames)
})
print(listOfBannedNames)
解决方法
那完全是关于异步行为。尝试进行以下操作:
func makeRequestToFirebase(completion: @escaping ([String]) -> Void) {
ref.observeSingleEvent(of: .value,with: {
snapshot in
var bannedNamesList = [String]()
for bannedNames in snapshot.children {
bannedNamesList.append((bannedNames as AnyObject).key)
}
listOfBannedNames = bannedNamesList
print(listOfBannedNames)
completion(listOfBannedNames) // - that will wait until the list of names arrives
})
}
然后使用功能:
makeRequestToFirebase() { names in
print(names)
workWithNames(names)
}
现在您可以根据需要使用它,例如:
func workWithNames(names: [String]) {
for name in names {
if name == "Alexander" {
print("One more Alexander found")
}
}
也请进一步了解escaping closures in Swift。