我正在创建一个测验应用程序,并且我有一个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
];
1条答案
按热度按时间83qze16e1#
使用Swift
Dictionary
而不是NSDictionary
,这段代码做了你问的事情-随机选择5个问题(你的例子只有5个问题,所以它们都被选择了):正如其他人评论的那样,字典可能不是解决这个问题的最佳数据结构。我认为更好的解决方案是使用
Question
s数组,以获得适当的类型安全和更可读的代码: