有效地将bool数组更改为字符串 - Swift

时间:2015-06-08 07:33:06

标签: arrays string swift

我正在开发一个测验项目并尝试将bool数组转换为字符串数组,以便我可以向用户显示他们的答案。我试图枚举问题数组,并提取所有用户的答案和正确的答案,并将它们附加到一个新的数组。

用户答案转到userAnswers

正确答案转到correctAnswers

然后它调用一个函数checkResults,它将检查用户错误或正确的答案数。

这是我被卡住的地方。我使用map函数来比较2个数组,然后给我一个名为answer的新数组。如果答案匹配,它将返回true,如果它们没有,它将返回false。我不完全确定如何将answer里面的结果转换为一个字符串数组以呈现给用户。

// 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()
     }
}

2 个答案:

答案 0 :(得分:1)

func checkResults() {
    let answer = map(zip(correctAnswers, userAnswers)){
        ($0.0 == $0.1) ? "correct" : "wrong"
    }
    var finalResults = answer.map({"The following answer is \($0)"})
}

希望这有帮助

答案 1 :(得分:0)

如果您只想将bool“更改”为字符串,可以再次使用map()

let answer  = [1,2,2]
let correct = [6,7,2]

func checkResults() {

    let answers = map(zip(correct, answer)) { $0.0 == $0.1 }
    let results = answers.map { $0 == true ? "You answered right!" : "Nope, wrong!" }

    map(results) { println($0) }
}

打印出来:

Nope, wrong!
Nope, wrong!
You answered right!