我有一个Firebase资源,它包含几个对象,我想使用Swift对它们进行迭代。我期望的工作如下(根据Firebase文档)
https://www.firebase.com/docs/ios-api/Classes/FDataSnapshot.html#//api/name/children
var ref = Firebase(url:MY_FIREBASE_URL)
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
println(snapshot.childrenCount) // I got the expected number of items
for rest in snapshot.children { //ERROR: "NSEnumerator" does not have a member named "Generator"
println(rest.value)
}
})因此,对Firebase返回的NSEnumerator对象进行Swift迭代似乎存在问题。
帮助是非常受欢迎的。
发布于 2014-12-07 11:36:28
如果我正确地阅读了文档,这就是你想要的:
var ref = Firebase(url: MY_FIREBASE_URL)
ref.observeSingleEvent(of: .value) { snapshot in
print(snapshot.childrenCount) // I got the expected number of items
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
print(rest.value)
}
}更好的办法可能是:
var ref = Firebase(url: MY_FIREBASE_URL)
ref.observeSingleEvent(of: .value) { snapshot in
print(snapshot.childrenCount) // I got the expected number of items
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? FIRDataSnapshot {
print(rest.value)
}
}第一个方法要求NSEnumerator返回所有对象的数组,然后可以按照通常的方式进行枚举。第二个方法一次从NSEnumerator中获取一个对象,并且可能更高效。
在这两种情况下,所枚举的对象都是FIRDataSnapshot对象,因此需要进行强制转换,以便可以访问value属性。
使用for-in 循环的:
自从在斯威夫特1.2天内写出最初的答案以来,语言已经发生了变化。现在可以使用直接与枚举数和case let一起工作的case let循环来分配类型:
var ref = Firebase(url: MY_FIREBASE_URL)
ref.observeSingleEvent(of: .value) { snapshot in
print(snapshot.childrenCount) // I got the expected number of items
for case let rest as FIRDataSnapshot in snapshot.children {
print(rest.value)
}
}发布于 2016-10-20 10:54:44
我刚刚把上面的答案转换为Swift 3:
ref = FIRDatabase.database().reference()
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount) // I got the expected number of items
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
print(rest.value)
}
})更好的办法可能是:
ref = FIRDatabase.database().reference()
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount) // I got the expected number of items
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? FIRDataSnapshot {
print(rest.value)
}
})发布于 2015-05-21 19:13:59
这是相当可读的,工作良好:
var ref = Firebase(url:MY_FIREBASE_URL)
ref.childByAppendingPath("some-child").observeSingleEventOfType(
FEventType.Value, withBlock: { (snapshot) -> Void in
for child in snapshot.children {
let childSnapshot = snapshot.childSnapshotForPath(child.key)
let someValue = childSnapshot.value["key"] as! String
}
})https://stackoverflow.com/questions/27341888
复制相似问题