本文介绍了在 Firebase 中迭代快照子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个对象的 Firebase 资源,我想使用 Swift 迭代它们.我期望的工作如下(根据 Firebase 文档)
https://www.firebase.com/docs/ios-api/Classes/FDataSnapshot.html#//api/name/children

I have a Firebase resource that contains several objects and I would like to iterate over them using Swift.What I expected to work is the following (according to the Firebase documentation)
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)
     }
 })

因此,Swift 迭代 Firebase 返回的 NSEnumerator 对象似乎存在问题.

So it seems there is a problem with Swift iterating over the NSEnumerator object returned by Firebase.

非常欢迎帮助.

推荐答案

如果我阅读了 文档 没错,这就是你想要的:

If I read the documentation right, this is what you want:

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 中一次获取一个对象,并且可能更有效.

The first method requires the NSEnumerator to return an array of all of the objects which can then be enumerated in the usual way. The second method gets the objects one at a time from the NSEnumerator and is likely more efficient.

在任何一种情况下,被枚举的对象都是 FIRDataSnapshot 对象,因此您需要强制转换,以便您可以访问 value 属性.

In either case, the objects being enumerated are FIRDataSnapshot objects, so you need the casts so that you can access the value property.

使用 for-in 循环:

Using for-in loop:

自从用 Swift 1.2 天写回原始答案以来,语言已经发展.现在可以使用 for in 循环,该循环直接与枚举器一起使用,以及 case let 来分配类型:

Since writing the original answer back in Swift 1.2 days, the language has evolved. It is now possible to use a for in loop which works directly with enumerators along with case let to assign the type:

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)
    }
}

这篇关于在 Firebase 中迭代快照子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:26