我对Append Firebase data to an array in Swift ios有疑问。当我使用queryEqualToValue
对超链接中给出的数据运行此代码时,它会给出queryCount
具有的元素数。但是,我希望将所有元素转换为数组。
例如,当我运行kısıt(3)
时,我希望在HHtype
的情况下获得所有Sesgrup = 3
值。并且,将这些元素存储在一个数组中。你能帮我解决这个问题吗?
我有以下数据:
{
"1400001" : {
"HHtype" : 3,
"Sesgrup" : 4,
"lg_Et harcaması" : 0,
"lg_Total Harcama" : 3.11
},
"1400002" : {
"HHtype" : 1,
"Sesgrup" : 4,
"lg_Et harcaması" : 1.2,
"lg_Total Harcama" : 3.15
},
"1400004" : {
"HHtype" : 3,
"Sesgrup" : 4,
"lg_Et harcaması" : 1.18,
"lg_Total Harcama" : 3.06
},
"1400005" : {
"HHtype" : 4,
"Sesgrup" : 3,
"lg_Et harcaması" : 2.21,
"lg_Total Harcama" : 3.74
},
....... (9000unit)
最后答案的代码:
func kısıt(sesNotoSet: UInt){
var rootRef: FIRDatabaseReference!
var haneRef: FIRDatabaseReference!
var numbersArray = [Int] ()
self.sesNo = sesNotoSet
rootRef = FIRDatabase.database().reference()
haneRef = rootRef.child("SES2014")
var queryCount : UInt = sesNotoSet
haneRef.queryOrderedByChild("Sesgrup").queryEqualToValue(queryCount).observeEventType(.ChildAdded, withBlock: { (snapshot) in
print(snapshot)
if let HHtypeDict = snapshot.value! as? [String:AnyObject]{
for each in HHtypeDict{
numbersArray.append(each.1["HHtype"] as! Int)
}
queryCount -= 1
if queryCount <= 0 {
print(numbersArray)
}
}
})
}
给定的错误:fatal error: unexpectedly found nil while unwrapping an Optional value
和print(snapshot)
仅为:
Snap (1400005) {
HHtype = 4;
Sesgrup = 3;
"lg_Et harcamas\U0131" = "2.21";
"lg_Total Harcama" = "3.74";
}
但是,快照应该有425个元素
答案 0 :(得分:0)
试试这个: -
func kısıt(sesNotoSet: UInt){
var rootRef: FIRDatabaseReference!
var haneRef: FIRDatabaseReference!
var numbersArray = [Int] ()
self.sesNo = sesNotoSet
rootRef = FIRDatabase.database().reference()
haneRef = rootRef.child("SES2014")
var queryCount : UInt = sesNotoSet
haneRef.queryOrderedByChild("Sesgrup").queryEqualToValue(queryCount).observeEventType(.ChildAdded, withBlock: { (snapshot) in
if let HHtypeDict = snapshot.value! as? [String:AnyObject]{
for each in HHtypeDict{
numbersArray.append(each.1["HHtype"] as! Int)
}
queryCount -= 1
if queryCount <= 0 {
print(numbersArray)
}
}
})
}