如何搜索字典?

时间:2019-06-25 04:11:25

标签: swift

创建了一些测验问题集,每个问题都有一个测验类别。如何搜索字典以打印与用户选择的测验类别相同的问题。

很抱歉,词典仍然是新手,仍在尝试将概念包裹在我的头上。

import UIKit

var list = [(categoryText: "Numbers", imageText: "Ten", audioText: "Ten"), (categoryText: "Numbers", imageText: "Eight", audioText: "Eight"), (categoryText: "Numbers", imageText: "Five", audioText: "Five"), (categoryText: "Colors", imageText: "Yellow", audioText: "Yellow"), (categoryText: "Colors", imageText: "Blue", audioText: "Blue"), (categoryText: "Colors", imageText: "Red", audioText: "Red") ]

let selectedCategory = "Numbers"

let q = list.filter { (($0 = "Numbers")) }

print(q)

能够在数组索引螺母上打印测验,希望能够选择具有相同值的问题。

1 个答案:

答案 0 :(得分:1)

import UIKit
var list = [(categoryText: "Numbers", imageText: "Ten", audioText: "Ten"), (categoryText: "Numbers", imageText: "Eight", audioText: "Eight"), (categoryText: "Numbers", imageText: "Five", audioText: "Five"), (categoryText: "Colors", imageText: "Yellow", audioText: "Yellow"), (categoryText: "Colors", imageText: "Blue", audioText: "Blue"), (categoryText: "Colors", imageText: "Red", audioText: "Red") ]

let selectedCategory = "Numbers"
var selectedCatagoryArray = [Any]()

for index in list {
    if index.categoryText == selectedCategory {
        selectedCatagoryArray.append(index)
    }
}

print(selectedCatagoryArray.description)

如果您的编码结构更好,我建议

struct Question {
    var categoryText : String?
    var imageText : String?
    var audioText : String?
}

var list = [Question(categoryText: "Numbers", imageText: "Ten", audioText: "Ten"), Question(categoryText: "Numbers", imageText: "Eight", audioText: "Eight"), Question(categoryText: "Numbers", imageText: "Five", audioText: "Five"), Question(categoryText: "Colors", imageText: "Yellow", audioText: "Yellow"), Question(categoryText: "Colors", imageText: "Blue", audioText: "Blue"), Question(categoryText: "Colors", imageText: "Red", audioText: "Red") ]

let selectedCategory = "Numbers"
var selectedCatagoryArray = [Question]()

for question in list {
    if question.categoryText == selectedCategory {
        selectedCatagoryArray.append(question)
    }
}

for element in selectedCatagoryArray {
    print("Question : \(element.categoryText) + with image Text : \(element.imageText) + with audioText : \(element.audioText)" )
}