我想在ios中开发一个测验应用程序。我看到了一个使用switch case的教程。现在我有几百多个问题。如何实现它,我需要我的问题是随机的。
答案 0 :(得分:1)
let randomIndex = Int(arc4random_uniform(UInt32(questionsArray.count)))
print(questionsArray[randomIndex])
使用上面的代码从数组中选择随机问题
答案 1 :(得分:0)
您可以使用此处的shuffle function随机播放您的问题。只需将其用作
即可var nums = [1, 2, 3, 4, 5]
nums.shuffle() // this will mutate and changed to shuffled array [5, 3, 1, 2, 4]
使用的确切扩展名如下:
extension MutableCollection where Indices.Iterator.Element == Index {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
guard d != 0 else { continue }
let i = index(firstUnshuffled, offsetBy: d)
swap(&self[firstUnshuffled], &self[i])
}
}
}