我正在尝试将元素追加到数组但它返回空数组。 我要做的是将与用户选择的标签匹配的元素放在一起。 为此,首先我创建了模型。
//Model
import UIKit
import Firebase
struct Team {
var key: String
var teamName: String
var league: String
var lat: Double
var lng: Double
init(snapshot: DataSnapshot) {
self.key = snapshot.key
self.teamName = (snapshot.value as! NSDictionary)["teamName"] as? String
self.league = (snapshot.value as! NSDictionary)["league"] as? String ?? ""
self.lat = (snapshot.value as! NSDictionary)["lat"] as? Double ?? 0
self.lng = (snapshot.value as! NSDictionary)["lng"] as? Double ?? 0
}
}
firebase结构看起来像这样。
{
"tags": {
"NewYork": {
uid1: 1
uid2: 1
uid3: 1
},
"baseball": {
uid1: 1
}
}
}
首先,我获取了与标签匹配的uids。然后根据与之匹配的uid检索团队的信息。如果同样的uid像上面的uid1一样进来,我想要Xcode打印一些东西。要做到这一点,我这样实现(有更好的方法吗?)但它从未被执行过,因为results.count
总是0,即使在追加后也是如此。然而,在追加方法(我在这里评论//)之后,它正确地返回了团队的信息。
func filterTeam(filterTag: FilteredTags) {
let tag = filterTag.selectedTag.components(separatedBy: "/") //this returns "NewYork" and "baseball"
var results = [Team]()
tag.forEach { (key) in
ref.child("tags").child(key).observe(.value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String:Any] else { return }
dictionary.forEach({ (uid,_) in
if results.count == 0 {
ref.child("teams").child(uid).observe(.value, with: { (snapshots) in
let team = Team(snapshot: snapshots)
results.append(team)
//here
print(results)
}, withCancel: nil)
} else {
for result in results {
if result.key == uid {
print("same uid!!")
} else {
ref.child("teams").child(uid).observe(.value, with: { (snapshots) in
let team = Team(snapshot: snapshots)
results.append(team)
}, withCancel: nil)
}
}
}
})
}, withCancel: nil)
}
}//func
如何正确追加并实现我想做的事情。 提前谢谢!