如何跟踪数组中的哪些项已经存在?

时间:2019-01-28 20:52:22

标签: ios swift

我有一个测验应用程序,可以生成一个随机问题。目前由于随机化,您有时可以多次回答相同的问题。我有一系列问题,我使用arc4Random方法在屏幕上生成随机问题。

我如何做到这一点,以便swift识别到已经存在一个问题并跳过该问题?我需要做一个if陈述吗?如果可以的话,我该如何编码?

var currentQuestion = Int(arc4random_uniform(31) + 1)
var rightAnswerPlacement:UInt32 = 0
var seconds = 30
var timer = Timer()
var score = 0
if (sender.tag == Int(rightAnswerPlacement)) {
    score += 1
    scoreLabel.text = "\(score)"
    seconds = 100
    currentQuestion = Int(arc4random_uniform(32) + 1)
} else {
    timer.invalidate()
    end()
}

2 个答案:

答案 0 :(得分:3)

var currentQuestion = Int(arc4random_uniform(36) + 1)
var rightAnswerPlacement:UInt32 = 0
var seconds = 30
var timer = Timer()
var score = 0
var asked = [Int]()

var recordData:String!

@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!

@IBOutlet weak var buttonOne: UIButton!
@IBOutlet weak var buttonTwo: UIButton!
@IBOutlet weak var buttonThree: UIButton!

@IBAction func answerButtons(_ sender: AnyObject) {

    if (sender.tag == Int(rightAnswerPlacement)) {

        score += 1
        scoreLabel.text = "\(score)"
        seconds = 100
        currentQuestion = Int(arc4random_uniform(36) + 1)

       while asked.contains(currentQuestion) {

            currentQuestion = Int(arc4random_uniform(36) + 1)
        }
        asked.append(currentQuestion)
        print(asked)

        if asked.count == questions.count {
            currentQuestion = 0
          return
        }

答案 1 :(得分:1)

您可以简单地将问题索引改组,然后处理该数组:

let questionCount = 32
let questionIndices = (0..<questionCount).shuffled()
for index in questionIndices {
    let question = questions[index]
    let answer = answers[index]
    // process the question
}

您可以相信shuffled()实现是随机的。