简体   繁体   English

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

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

Hi guys I am in big trouble. 大家好,我很麻烦。 Here is my code: 这是我的代码:

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
           }

I am getting the error Int is not convertible to DictionaryIndex and I don't understand what that means. 我收到错误Int无法转换为DictionaryIndex,我不明白这意味着什么。 Shouldn't I be able to access my dictionary by index. 我不应该能够通过索引访问我的词典。

hard to say, what are you trying to do. 很难说,你想做什么。 here is an example, how to access dictionary (unordered collection of key, value pairs) by different ways 这是一个示例,说明如何通过不同方式访问字典(键,值对的无序集合)

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")
*/

So there are a couple of things that are going on here that my not be in the way you want them. 因此,这里发生了几件事,但并非您想要的那样。 First your main question you are trying to iterate this dictionary like it is a list ie let list = [apple, banana, orange] this list has an index that you could iterate through similarly to what you are doing. 首先,您要尝试对这本字典进行迭代的主要问题就好像它是一个列表一样,即let list = [apple, banana, orange]此列表具有一个index ,您可以像正在做的那样迭代该index

for fruit in list {
    print(fruit)
 }

 This would print:
 apple
 banana
 orange

Where as dictionarys are more key:value based. 其中字典更key:value基于key:value

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

What I would suggest is that you make a list of dictionary but structure you data a little differently more like 我的建议是,您列出一个字典列表,但数据的结构稍有不同,例如

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

so this lets you have a list of dictionary each dictionary has two keys (question and answer) and now you can iterate through all of them and you questions and answers will be paired together. 因此,这使您可以找到字典列表,每个字典都有两个键(问题和答案),现在您可以遍历所有键,问题和答案将配对在一起。

or alternatively you could make a struct to represent your question answer combo then have a list of those structs. 或者,您可以制作一个struct来表示您的问题答案组合,然后列出这些结构。 This makes things nice because you can use dot syntax to access the items within the 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

let me know if you have any other questions? 让我知道您还有其他问题吗? 🤓 🤓

To solve your score logic you have two lists. 为了解决分数逻辑,您有两个列表。 The user selects an answer and you already know the index of the question so you just need to check that their answer is the same as the answer for the question at the same index. 用户选择了一个答案,并且您已经知道问题的索引,因此您只需要检查他们的答案是否与该问题的答案在相同的索引处相同即可。 so look kinda like this 所以看起来像这样

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

The other answers here are correct, and I particularly like Daniel Leonard's answer, as it provides a good way to organize your questions and answers. 这里的其他答案都是正确的,我特别喜欢Daniel Leonard的答案,因为它提供了组织问题和答案的好方法。


First of all, I would like say that listOfQuestionsAndAnswers is not a list - it's actually a Dictionary. 首先,我想说listOfQuestionsAndAnswers不是列表-它实际上是字典。 In particular, it is a Dictionary<String, String> , ie it's key must be a string, and it's value must be a string. 特别是,它是Dictionary<String, String> ,即它的键必须是一个字符串,并且它的值必须是一个字符串。

But not to worry! 但是不用担心! The Dictionary type conforms to the protocol CollectionType , which means that we can use 'traditional' means to index it. Dictionary类型符合协议CollectionType ,这意味着我们可以使用“传统”方式对其进行索引。 It does not mean we can access it with an Int . 并不意味着我们可以用一个访问它Int But we can access it with an index of type Dictionary.Index . 但是我们可以使用Dictionary.Index类型的索引访问它。

How is that done? 怎么做?

  1. Grab the index from the dictionary. 从字典中获取索引。
  2. Iterate over the contents, by using the index to grab the values. 通过使用索引获取值来遍历内容。
  3. Get the next index by calling index.successor() 通过调用index.successor()获得下一个索引
  4. Check that the index is not invalid, by checking that it is not equal to the end index. 检查索引不是无效的,通过检查,这等于结束索引。

Code

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

You can see that when we access the contents of the dictionary using an index, we retrieve a tuple. 您可以看到,当我们使用索引访问字典的内容时,我们将检索一个元组。 .0 is the key, and .1 is the value, in this case, corresponding to the question and answer respectively. 在这种情况下, .0是键,而.1是值,分别对应于问题和答案。

Note: Indexes from a dictionary are not guaranteed to be ordered - they could come out in a different order every time! 注意:不能保证字典中的索引是有序的-它们每次可能以不同的顺序出现! If you want an ordered collection, then you should use an array. 如果要有序集合,则应使用数组。

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

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