我如何正确使用map& zip来比较我的Structs数组中的属性?

时间:2015-07-29 06:35:20

标签: swift dictionary boolean zip

我使用以下行将测验中的correctAnswers与用户提交的答案进行比较。

它返回一个bool数组,然后我会搜索并计算它们得到的真实数和假数(true = correct和false = wrong)。

let totalResults = map(zip(correctAnswers, userAnswers)){$0.0 == $0.1}

我将所有测验信息存储在一组结构中,例如 struct questionInfo {

    var question : String!
    var answer : Bool!
    var userAnswer : Bool!
    var explanation : String!


    init(question: String, answer: Bool, explanation: String!) {
        self.question = question
        self.answer = answer
        self.explanation = explanation
    }
}


// These are the questions that will be shuffled before the quiz begins
var quizQuestion =

 [
    questionInfo(question: "Question 0", answer: true, explanation: ""),
    questionInfo(question: "Question 1", answer: true, explanation: ""),
    questionInfo(question: "Question 2", answer: true, explanation: ""),
    questionInfo(question: "Question 3", answer: true, explanation: ""),
    questionInfo(question: "Question 4", answer: true, explanation: "")
                                                                        ]

如何将结构数组中的信息输入到我的地图和&拉链线。我尝试使用for循环将所有答案附加到数组中,但它看起来非常混乱。

为了澄清我想做这样的事情:

let totalResults = map(zip(quizQuestion[x].answer, quizQuestion[x].userAnswer)){$0.0 == $0.1}

1 个答案:

答案 0 :(得分:2)

如果所有信息都在单zip()中,则您不需要quizQuestion 数组,仅map()

let totalResults = map(quizQuestion) { $0.answer == $0.userAnswer }   // [Bool]

然后,您可以使用reduce()计算正确答案的数量:

let numberOfCorrectResults = reduce(totalResults, 0) { $0 + Int($1) } // Int

这是Swift 1.2语法,对于Xcode 7 beta的Swift 2来说,它将是

let totalResults = quizQuestion.map { $0.answer == $0.userAnswer }   // [Bool]
let numberOfCorrectResults = totalResults.reduce(0) { $0 + Int($1) } // Int