我有这个数组,我想按顺序在文本标签中打印问题。是否有一个功能可以读取每个问题的ID并对其进行排序?

这是我的代码:

struct Question {
    let question: String
    let id: Int
    let answers: [ Answer ]
}

struct Answer {
    let id: String
    let answer: String
    let isSelected: Bool
}

struct allQuestions {

    let Questions = [

        Question(question: "The easiest way to learn is:", id: 1, answers: [
            Answer(id: "V", answer: "By viewing, reading, and observing how the others carry out certain tasks", isSelected: false),
            Answer(id: "A", answer: "By listening, discussing and doing according to verbal instructions" , isSelected: false),
            Answer(id: "K", answer: "By dping and experimenting by myself", isSelected: false)
        ]),

最佳答案

按ID对问题进行排序

let sorted =  questions.sorted(by: { $0.id < $1.id })

之后,您可以循环数组
for question in sorted
{
    print(question.id)
}

09-30 22:54
查看更多