简体   繁体   中英

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. 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.

for fruit in list {
    print(fruit)
 }

 This would print:
 apple
 banana
 orange

Where as dictionarys are more key:value based.

 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. This makes things nice because you can use dot syntax to access the items within the struct

 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.


First of all, I would like say that listOfQuestionsAndAnswers is not a list - it's actually a Dictionary. In particular, it is a Dictionary<String, String> , ie it's key must be a string, and it's value must be a string.

But not to worry! The Dictionary type conforms to the protocol CollectionType , which means that we can use 'traditional' means to index it. It does mean we can access it with an Int . 意味着我们可以用一个访问它IntBut we 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()
  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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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