Int不能转换为Dictionary <string,string =“”>

时间:2016-02-25 21:21:54

标签: ios swift dictionary

此行有错误(questionField.text = listOfQuestionsAndAnswers [currentQuestionIndex])(Int不能转换为Dictionary)。 此外,我希望所有问题一个接一个地显示,并在最后一个问题之后,&#34;谁是保罗&#34;应该再次显示......

let listOfQuestionsAndAnswers = ["Who’s Paul?": "An American", "Who’s Joao?": "A Bresilian", "Who’s Riccardo?": "An Italian"]

@IBAction func answerButtonTapped (sender: AnyObject){

    for (Question, rightAnswer) in listOfQuestionsAndAnswers {

        questionField.text = listOfQuestionsAndAnswers[currentQuestionIndex]
        if currentQuestionIndex <= listOfQuestionsAndAnswers.count
        {
            currentQuestionIndex = (++currentQuestionIndex) % listOfQuestionsAndAnswers.count
            answerBut.setTitle("ANSWER", forState: UIControlState.Normal)
        }
        else
        {
            (sender as UIButton).userInteractionEnabled = false
        }
    }
}

我收到错误Int不能转换为DictionaryIndex,我不明白这意味着什么。我不能通过索引访问我的字典。

3 个答案:

答案 0 :(得分:1)

您无法通过Int下标字典。字典包含键和值,并由键下标。在这种情况下,您的listOfQuestionsAndAnswers是一个字典,其中键和值都是字符串。

如果您想通过Int下标,请考虑使用(String, String)元组数组。

如果要使用字典,则必须通过其键从字典中检索值:

listOfQuestionsAndAnswers["Who’s Paul?"] // "An American"

答案 1 :(得分:0)

listOfQuestionsAndAnswers不是数组是字典而listOfQuestionsAndAnswers [someIntIndex]不起作用,因为你的键是字符串

    let listOfQuestionsAndAnswers = ["Who’s Paul?": "An American", "Who’s Joao?": "A Bresilian", "Who’s Riccardo?": "An Italian"]

    @IBAction func answerButtonTapped (sender: AnyObject){

        for (Question, rightAnswer) in listOfQuestionsAndAnswers {

            //questionField.text = listOfQuestionsAndAnswers[currentQuestionIndex] 
//changed to this
questionField.text = Quesition
            if currentQuestionIndex <= listOfQuestionsAndAnswers.count
            {
                currentQuestionIndex = (++currentQuestionIndex) % listOfQuestionsAndAnswers.count
                answerBut.setTitle("ANSWER", forState: UIControlState.Normal)
            }
            else
            {
                (sender as UIButton).userInteractionEnabled = false
            }
        } }

答案 2 :(得分:0)

您的listOfQuestionsAndAnswers是Dictionary<String:String>类型的字典。您不能使用类似该行的整数索引使用字符串键索引到字典中。

你的for循环是将每个键/值对提取到一个元组,这很好,但字典没有数字索引。事实上,字典是完全无序的。如果你想要一组可以循环的问题和答案,使用索引来获取使用索引等的特定问题/答案对,你应该考虑一个元组数组或一组问题/答案结构,或其他一些数据结构。