我正在Xcode中创建一个问答游戏,我在测验完成后有一个屏幕,显示5个问题(来自70+的数组)和相应的正确答案(答案)以及用户选择的答案( UserAnswer)。
我目前有正确答案的标签集(CorrectAnswer)和用户答案YourAnswer的单独标签集合。我想连续打印5个标签(QuestionName,YourAnswer,CorrectAnswer)的每个集合中为每个数组存储的所有5个值。
我对编码很新,所以任何有关在循环中使用数组的帮助都会受到赞赏。
First View Controller:
struct Question {
var Question : String
var Answers : [String]!
var Answer : Int!
var UserAnswer : Int!
}
var Questions = [Question]()
第二视图控制器:
class ScoreViewController: UIViewController {
var Questions = [Question]()
var CorrectAnswerTotal = Int()
var QuestionNumberTotal = Int()
let TOTAL_QUESTIONS = 0
var AnswerNumber = Int()
@IBOutlet var QuestionName: [UILabel]!
@IBOutlet var YourAnswer: [UILabel]!
@IBOutlet var CorrectAnswer: [UILabel]!
for i in 0..<Questions.count {
var q = Questions[i].Question
var ai = Questions[i].Answer
var a = Questions[i].Answers[ai]
var uai = Questions[i].UserAnswer
var ua = Questions[i].Answers[uai]
//This is where the error is
if QuestionNumberTotal < TOTAL_QUESTIONS {
if (ai != uai){
QuestionName.text = Questions[i].Question
YourAnswer.text = Questions[i].UserAnswer
CorrectAnswer.text = Questions[i].Answer
}
答案 0 :(得分:0)
随意询问是否有不清楚的事情。
struct Question {
var question: String
var answers: [String]
var correctAnswer: Int
var userAnswer: Int
}
var questions = [Question]()
var correctAnswerTotal = 0
@IBOutlet var questionName: [UILabel]!
@IBOutlet var yourAnswer: [UILabel]!
@IBOutlet var correctAnswer: [UILabel]!
override func viewDidLoad() {
super.viewDidLoad()
// fill it with some examples
questions.append(Question(question: "Question 1?", answers: ["Answer 1", "Answer 2", "Answer 3", "4", "Answer 5"], correctAnswer: 0, userAnswer: 1))
questions.append(Question(question: "Question 2?", answers: ["Answer 1", "Answer 2", "Answer 3", "4", "Answer 5"], correctAnswer: 1, userAnswer: 2))
questions.append(Question(question: "Question 3?", answers: ["Answer 1", "Answer 2", "Answer 3", "4", "Answer 5"], correctAnswer: 3, userAnswer: 3))
// assure, that the necessary amount of labels exists
guard questionName.count >= questions.count
&& yourAnswer.count >= questions.count
&& correctAnswer.count >= questions.count else {
print("Not enough labels.")
return
}
// starts at 0 and ends at last-1
for i in 0..<questions.count {
let q = questions[i]
let user = q.answers[q.userAnswer]
let correct = q.answers[q.correctAnswer]
// set labels texts
questionName[i].text = q.question
yourAnswer[i].text = user
correctAnswer[i].text = correct
// correct answer is green, incorrect answer is red
if q.correctAnswer == q.userAnswer {
correctAnswerTotal += 1
yourAnswer[i].textColor = UIColor.green
} else {
yourAnswer[i].textColor = UIColor.red
}
}
}