【问题标题】:NSObject has no subscript membersNSObject 没有下标成员
【发布时间】:2017-03-31 01:23:18
【问题描述】:

我在尝试从 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
    }
}

} //}

【问题讨论】:

    标签: swift xcode


    【解决方案1】:

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

    【讨论】:

    • 我把它放在我的代码中但是我得到了这个:“条件绑定的初始化器必须具有可选类型,而不是字符串
    • 在这一行let Correct = dataDict["Correct"] as! String,对吧?我刚刚更新了。
    • 现在附加有一个错误,无法将String类型的值转换为预期的参数类型[string]
    • 还是同样的问题?
    • 但现在它说不能将 String 类型的值转换为 int 类型
    猜你喜欢
    • 2017-06-20
    • 2014-12-17
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2017-02-18
    • 2017-07-18
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多