swift 有没有简单的方法来 Shuffle 一个NSDictionary?

o7jaxewo  于 2023-04-10  发布在  Swift
关注(0)|答案(1)|浏览(103)

我正在创建一个测验应用程序,并且我有一个NSDictionary,其中键为问题,值为true或false(答案)。我想从这个NSDictionary中随机选择5个值。如何将NSDictionary随机选择值?
这是NSDictionary

let questions: NSDictionary = [
    "A habit is a behavior that has been repeated enough times to become automatic.": true,
    "Spending a conversation talking mostly about yourself is a good way to influence people.": false,
    "In the 7 Habits of Highly Effective People, the Circle of Influence is all of the things inside an individual's control.": true,
    "In The Outliers by Malcolm Gladwell, the author states that the number of hours you practice is more important than your natural talent": true,
    "Think and Grow Rich by Napoleon Hill is based on the idea that anyone can achieve success if they have the right mindset.": true
];
83qze16e

83qze16e1#

使用Swift Dictionary而不是NSDictionary,这段代码做了你问的事情-随机选择5个问题(你的例子只有5个问题,所以它们都被选择了):

let questions: Dictionary = [
    "A habit is a behavior that has been repeated enough times to become automatic.": true,
    "Spending a conversation talking mostly about yourself is a good way to influence people.": false,
    "In the 7 Habits of Highly Effective People, the Circle of Influence is all of the things inside an individual's control.": true,
    "In The Outliers by Malcolm Gladwell, the author states that the number of hours you practice is more important than your natural talent": true,
    "Think and Grow Rich by Napoleon Hill is based on the idea that anyone can achieve success if they have the right mindset.": true
]

let randomQuestions = questions.keys.shuffled().prefix(5)

for question in randomQuestions {
    // It is safe to force unwrap the answer because we know that `question` exists in the keys
    let answer = questions[question]
    print("Q: \(question), A: \(answer)")
}

正如其他人评论的那样,字典可能不是解决这个问题的最佳数据结构。我认为更好的解决方案是使用Question s数组,以获得适当的类型安全和更可读的代码:

struct Question {
    let title: String
    let answer: Bool
}

let questions = [
    Question(title: "A habit is a behavior that has been repeated enough times to become automatic.", answer: true),
    Question(title: "Spending a conversation talking mostly about yourself is a good way to influence people.", answer: false),
    Question(title: "In the 7 Habits of Highly Effective People, the Circle of Influence is all of the things inside an individual's control.", answer: true),
    Question(title: "In The Outliers by Malcolm Gladwell, the author states that the number of hours you practice is more important than your natural talent", answer: true),
    Question(title: "Think and Grow Rich by Napoleon Hill is based on the idea that anyone can achieve success if they have the right mindset.", answer: true)
]

let randomQuestions = questions.shuffled().prefix(5)

for question in randomQuestions {
    print("Q: \(question.title), A: \(question.answer)")
}

相关问题