在我的firebase数据库中,我有以下结构
-Questions
--Food
--- 0
----- question
----- Answer
--- 1
----- question
----- Answer
--- 2
----- question
----- Answer
--- 5
----- question
----- Answer
--- 8
----- question
----- Answer
--- 12
----- question
----- Answer
--Comedy
--Science
--Maths
如您所见,有几个问题和答案存储在类别下的节点ID下。我正在获取特定ID的快照,如下所示:
let queryRef = FIRDatabase.database().reference().child("Questions").child(category).child(questionID)
queryRef.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.value)
})
这给了我:
Optional({
answers = (
"T.S. Eliot",
"S.L Luther",
"S. Maguire",
"C. Dickens"
);
question = "Who Wrote (Old Possums Book Of Practical Cats)?";
})
现在,我想要做的是能够抓住问题和答案并将它们变成变量。
我认为这是正确的方法:
for item in snapshot.children {
let question = item["question"] as? String
}
然而它返回错误:
键入' NSFastEnumerationIterator.Element' (又名'任何')没有下标成员
如何通过快照中的键访问值,如此
问题
答案[0]
答案[1]
答案[2]
答案[3]
这样我可以单独将它们添加到变量中吗?
提前感谢。
我试过了:
if let dict = snapshot.value as? NSDictionary, let question = dict["question"] as? String {
print("Question is: \(question)")
}
哪个输出:
问题是:谁写了(实用猫的老负鼠书)?
但是,当我尝试使用这种方式获得可能的答案时:
if let dict = snapshot.value as? NSDictionary, let question = dict["question"] as? String, let answers = dict["answers"] as? String {
print("Question is: \(question) and answers are\(answers)")
}
没有输出。