【问题标题】:Efficiently change an array of bools to string - Swift有效地将布尔数组更改为字符串 - Swift
【发布时间】: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()
     }
}

【问题讨论】:

  • 你应该发布你的数组的样子

标签: arrays string swift


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

希望对你有帮助

【讨论】:

    【解决方案2】:

    如果您只想将布尔值“更改”为字符串,您可以再次使用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!
    

    【讨论】:

    • 非常感谢您的帮助!这个解决方案和其他解决方案都教会了我很多东西!
    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 2020-06-21
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多