我去年在Swift 2中做了一个测验游戏,现在我需要再次使用它,当我将其转换为Swift 3时,答案随机化了......这是一个示例问题结构......
Questions = [Question(Question: "What is the Biggest Hit of Bing Crosby?" , Answers: ["Swinging on a Star", "Now is the Hour", "White Christmas", "Beautiful Dreamer"], Answer: 2),]
这是我将问题随机化并将它们放入标签
的地方func PickQuestions() {
counter += 1
score += 1
scoreLbl.text = "\(score)"
restartBtn.isEnabled = false
if Questions.count > 0 && counter <= 15 {
QNumber = Int(arc4random_uniform(UInt32(Questions.count)))
QLabel.text = Questions[QNumber].Question
AnswerNumber = Questions[QNumber].Answer
for i in 0..<Buttons.count{
Buttons[i].setTitle(Questions[QNumber].Answers[i], for: UIControlState())
}
Questions.remove(at: QNumber)
}
}
我必须手动更改以下行,这可能会导致问题......
QNumber = Int(arc4random_uniform(UInt32(Questions.count)))
到
QNumber = random() % Questions.count
谢谢
答案 0 :(得分:-1)
数组是无序集合,这意味着它们的顺序可能会在您不知情的情况下发生变化。你最好的选择是创建一个包含结构的单个数组,该结构包含问题和答案,如下所示:
struct QuizItem {
var question: String!
var answer: String!
var answerOptions: [String]!
init(q: String, a: String, aOptions:[String]) {
self.question = q
self.answer = a
}
}
将您的声明更改为如下所示:
let items = [QuizItem(...)]
您的代码如下:
func PickQuestions() {
counter += 1
score += 1
scoreLbl.text = "\(score)"
restartBtn.isEnabled = false
if items.count > 0 && counter <= 15 {
QNumber = Int(arc4random_uniform(UInt32(Questions.count)))
let item = items[QNumber]
QLabel.text = item.question
for i in 0..<Buttons.count{
Buttons[i].setTitle(item.answerOptions[i], for: UIControlState())
}
items.remove(at: QNumber)
}
}
另外,有点挑剔但值得强调。 Swift是一种驼峰案例语言,尽管这条规则并非一成不变,但您应该尝试并坚持使用广泛认可的编码实践。