目前正在制作一个小测验应用程序,我将问题存储在一个数组中。
这是我正在尝试的方法,但只显示一个问题。
var questionList = ["Question1","Question2","Question3","Question4","Question5"]
print(questionList.randomElement()!)
如何从中选择几个随机元素?
让我们说我有100个问题,我只想显示一组随机的10个问题?
答案 0 :(得分:5)
Shuffle数组,并使用prefix(_:)
获取前10个元素如果最大长度超过了 集合,结果包含集合中的所有元素。
let arr = Array(1..<100)
let shuffledArr = arr.shuffled()
print(shuffledArr.prefix(10))//[35, 61, 9, 80, 68, 37, 22, 79, 57, 32]
确保数组长度大于子数组计数
let questionList = ["Question1","Question2","Question3","Question4","Question5"]
print(questionList.shuffled().prefix(2))//["Question5", "Question2"]