簡體   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