繁体   English   中英

Int不能转换为DictionaryIndex <String, String>

[英]Int is not convertible to DictionaryIndex<String, String>

大家好,我很麻烦。 这是我的代码:

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,我不明白这意味着什么。 我不应该能够通过索引访问我的词典。

很难说,你想做什么。 这是一个示例,说明如何通过不同方式访问字典(键,值对的无序集合)

let dict = ["a":"A","b":"B"]
for (k,v) in dict {
    print(k,v)
}
/*
b B
a A
*/

dict.forEach { (d) -> () in
    print(d.0,d.1)
}
/*
b B
a A
*/

dict.enumerate().forEach { (e) -> () in
    print(e.index,e.element,e.element.0,e.element.1)
}
/*
0 ("b", "B") b B
1 ("a", "A") a A
*/

dict.indices.forEach { (di) -> () in
    print(dict[di],dict[di].0,dict[di].1)
}
/*
("b", "B") b B
("a", "A") a A
*/

dict.keys.forEach { (k) -> () in
    print(k,dict[k])
}
/*
b Optional("B")
a Optional("A")
*/

因此,这里发生了几件事,但并非您想要的那样。 首先,您要尝试对这本字典进行迭代的主要问题就好像它是一个列表一样,即let list = [apple, banana, orange]此列表具有一个index ,您可以像正在做的那样迭代该index

for fruit in list {
    print(fruit)
 }

 This would print:
 apple
 banana
 orange

其中字典更key:value基于key:value

 struct food {
     catigory:String()
     type:String()
 }

我的建议是,您列出一个字典列表,但数据的结构稍有不同,例如

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

因此,这使您可以找到字典列表,每个字典都有两个键(问题和答案),现在您可以遍历所有键,问题和答案将配对在一起。

或者,您可以制作一个struct来表示您的问题答案组合,然后列出这些结构。 这使事情变得很不错,因为您可以使用dot语法来访问结构中的项目

 struct dictionaryStruct {
    var question:String
    var answer:String
 }

var listOfQuestionAnswers = [dictionaryStruct]()

func makeList(quest:String,answer:String){
    let dict = dictionaryStruct.init(question: quest, answer: answer)
    listOfQuestionAnswers.append(dict)
}

makeList("Who’s Paul?", answer: "An American")
makeList("Who’s Joao?", answer: "A Bresilian")
makeList("Who’s Riccardo?", answer: "An Italian")

for entry in listOfQuestionAnswers {
    print("\(entry.question), \(entry.answer)")
}    


---------- Console Output:
      Who’s Paul?, An American
      Who’s Joao?, A Bresilian
      Who’s Riccardo?, An Italian

让我知道您还有其他问题吗? 🤓

为了解决分数逻辑,您有两个列表。 用户选择了一个答案,并且您已经知道问题的索引,因此您只需要检查他们的答案是否与该问题的答案在相同的索引处相同即可。 所以看起来像这样

if answer == listOfAnswers[currentQuestionIndex]{
    score ++
}

这里的其他答案都是正确的,我特别喜欢Daniel Leonard的答案,因为它提供了组织问题和答案的好方法。


首先,我想说listOfQuestionsAndAnswers不是列表-它实际上是字典。 特别是,它是Dictionary<String, String> ,即它的键必须是一个字符串,并且它的值必须是一个字符串。

但是不用担心! Dictionary类型符合协议CollectionType ,这意味着我们可以使用“传统”方式对其进行索引。 并不意味着我们可以用一个访问它Int 但是我们可以使用Dictionary.Index类型的索引访问它。

怎么做?

  1. 从字典中获取索引。
  2. 通过使用索引获取值来遍历内容。
  3. 通过调用index.successor()获得下一个索引
  4. 检查索引不是无效的,通过检查,这等于结束索引。

// Not a list of questions, it's a dictionary.
let questionsAndAnswers = ["Who’s Paul?": "An American", 
                           "Who’s Joao?": "A Bresilian", 
                           "Who’s Riccardo?": "An Italian"]

var index = questionsAndAnswers.startIndex
while index != questionsAndAnswers.endIndex {
    let question = questionsAndAnswers[index].0
    let answer = questionsAndAnswers[index].1
    print("Question: \(question); Answer: \(answer)")
    index = index.successor()
}

您可以看到,当我们使用索引访问字典的内容时,我们将检索一个元组。 在这种情况下, .0是键,而.1是值,分别对应于问题和答案。

注意:不能保证字典中的索引是有序的-它们每次可能以不同的顺序出现! 如果要有序集合,则应使用数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM