【发布时间】:2015-06-08 07:33:06
【问题描述】:
我正在做一个测验项目,并尝试将布尔数组转换为字符串数组,以便我可以向用户展示他们的答案。我试图枚举问题数组并提取所有用户答案和正确答案并将它们附加到新数组中。
用户的答案转到 userAnswers
正确答案转到正确答案
然后它调用一个函数 checkResults 来检查用户答错或正确的答案。
这就是我卡住的地方。我使用了一个 map 函数来比较这两个数组,然后给我一个新的数组,称为 answer。如果答案匹配,它将返回 true,如果不匹配,则返回 false。我不完全确定如何将答案中的结果转换为字符串数组以呈现给用户。
// My Arrays
class QuizQuestion {
let question: String!
let answer: Bool!
let explanation: String!
var usersAnswer: Bool?
init(question: String, answer: Bool, explanation: String) {
self.question = question
self.answer = answer
self.explanation = explanation
}
}
let questions = [
QuizQuestion(question: "Do I like coffee?", answer: true, explanation: "Because it's awesome!"),
QuizQuestion(question: "Is bacon god's gift to mankind?", answer: true, explanation: "Because it's awesome!"),
QuizQuestion(question: "Should I take a nap right now?", answer: true, explanation: "You gotta review some code!"),
]
var userAnswers: [Bool] = []
var correctAnswers: [Bool] = []
// Submit Functions
func checkResults() {
let answer = map(zip(correctAnswers, userAnswers)){$0.0 == $0.1}
var finalResults = answer.map({"The following answer is \($0)"})
}
@IBAction func submitAll(sender: UIButton) {
let hasAnsweredAllQuestions = questions.reduce(true) { (x, q) in x && (q.usersAnswer != nil) }
println("has user answered all questions?: \(hasAnsweredAllQuestions)")
for (index, _) in enumerate(questions) {
userAnswers.append(questions[index].usersAnswer!)
correctAnswers.append(questions[index].answer)
}
if correctAnswers.count == 3 {
checkResults()
}
}
【问题讨论】:
-
你应该发布你的数组的样子