【问题标题】:Extract text from array by id按 id 从数组中提取文本
【发布时间】:2020-03-13 03:44:36
【问题描述】:

我有这个数组,我想按顺序在文本标签中打印问题。有没有可以读取每个问题的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)
        ]),

【问题讨论】:

  • 你试过了吗?
  • 我是 swift 的初学者,我目前一直在尝试提取问题 ID 并打印问题
  • Questions.sort { $0.id < $1.id }
  • 结构名称应以大写字母开头。变量名应以小写字母开头

标签: ios arrays swift xcode


【解决方案1】:

按 id 对问题进行排序

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

之后你可以循环数组

for question in sorted 
{ 
    print(question.id) 
}

【讨论】:

    【解决方案2】:

    这就是你需要做的所有事情:

    let orderedQuestions = questions.answers.sorted { lhs, rhs in
    
        return lhs.id < rhs.id
    }
    

    【讨论】:

    • 短版let ordered = questions.answers.sorted { $0.id &lt; $1.id }
    猜你喜欢
    • 2019-07-26
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多