我遇到了尝试从firebase检索数据的问题。我一直收到一个错误,说NSObject在尝试追加时没有下标成员?目前firebase正在举行一个问题,一系列不同的答案和一个正确答案。
class QuestionList
{
//properties
public static var Username: String = ""
private static var quiz = [Question]()
static func getDummyQuestions()->[Question]
{
//create some dummy data for the model
var ref: FIRDatabaseReference!
var refHandle: UInt!
ref = FIRDatabase.database().reference() //reference
refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
let dataDict = snapshot.value as? NSObject
//let value = snapshot.value as? NSDictionary
//let quest = value?["Question"] as! String
//let Answers = value?["Answers"] as! String
//let Correct = value?["Correct"] as! String
//quiz.append(Question(q: quest, a:[Answers], c: Correct))
quiz.append(Question(q: dataDict["Question"], a: dataDict["Answers"], c: dataDict["Correct"]))
//quiz.append(Question(q: "hello", a: ["short long", "short char", "short float", "short int"], c: 2 ))
//quiz.append(Question(q: "bye", a: ["short short", "short int", "short float", "short int"], c: 2 ))
print (dataDict)
})
return quiz
}
}
class Question
{
var quest:String
var answers:[String]
var correct:Int
init(q: String, a:[String], c:Int)
{
quest = q
answers = a
correct = c
}
func isCorrectQuestion(itemSelected: String)->Bool {
if (itemSelected == answers[correct]) {
return true
} else {
return false
}
}
} //}
答案 0 :(得分:0)
将snapshot
投射到字典:let dataDict = snapshot.value as? [String: Any]
refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
if let dataDict = snapshot.value as? [String: Any] {
if let quest = dataDict["Question"] as? String,
let Answers = dataDict["Answers"] as? [String],
let Correct = dataDict["Correct"] as? Int {
quiz.append(Question(q: quest, a: Answers, c: Correct))
}
}
print (dataDict)
})