【问题标题】:How to pull random questions for quizz app from an array in questionbank? Swift如何从问题库中的数组中提取测验应用程序的随机问题?迅速
【发布时间】:2019-08-07 12:28:49
【问题描述】:

所以我正在处理我的第一个个人项目(包括测验功能),同时参加快速课程。我想弄清楚如何随机化数组。

我找到了一些解释类似内容的视频,但似乎没有什么对我有用。

这是我需要改组的问题库之一的示例。

class ImageQuestionBank {
var list = [ImageQuestion] ()
init () {
    let item = ImageQuestion(qtext: "Example Question?", image: "image1", correctAnswer: true)
    list.append(item)
    list.append(ImageQuestion(qtext: "Example Question?", image: "image2", correctAnswer: false))
    list.append(ImageQuestion(qtext: "Example Question?", image: "image3", correctAnswer: true))
    }
}

【问题讨论】:

  • 为什么 shuffled() 或 shuffle() 不适合你?

标签: arrays swift random shuffle


【解决方案1】:

正如@Retterdesdialogs 评论所暗示的,您可以使用shuffled() 返回序列的元素,打乱。 或shuffle() 用于就地打乱

但是,不要对数组进行洗牌,这是一项昂贵的操作,而是使用 Int random 函数来获取给定范围之间的随机 int。

let randomInt = Int.random(in: 0..<list.count) // this will give a random int value between 0 and list count.

现在使用randomInt 获取项目

【讨论】:

  • 谢谢!这正是我想要的。
【解决方案2】:

使用arc4random_uniform(list.count) 为list 对象生成随机索引。但要确保问题不会重复,请维护askedQuestionList。在向用户显示问题之前,请检查askedQuestionList 中的问题条目。

另一种打乱你的问题数组的方法,检查这个question。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多