如何将字典值传递给数组?

时间:2018-07-16 11:48:38

标签: ios arrays dictionary swift3

var params = [[String:Any]]()

for i in 0 ..< QuesCount  {
    self.params.append([self.key1[i] : self.value1[i],
                            self.key2[i] : self.value2[i]])
}

输出:

self.params= [["answer[0][question_id]": "1", "answer[0][ans_id]": "21"], ["answer[1][question_id]": "2", "answer[1][ans_id]": "26"], ["answer[2][ans_id]": "36", "answer[2][question_id]": "5"], ["answer[3][ans_id]": "40", "answer[3][question_id]": "6"], ["answer[4][question_id]": "7", "answer[4][ans_id]": "41"], ["answer[5][question_id]": "8", "answer[5][ans_id]": "46"], ["answer[6][ans_id]": "49", "answer[6][question_id]": "9"], ["answer[7][question_id]": "10", "answer[7][ans_id]": "54"], ["answer[8][question_id]": "11", "answer[8][ans_id]": "57"]]

但是问题是我想要:

理想的输出:

["answer[0][question_id]": "1", "answer[0][ans_id]": "21"], ["answer[1][question_id]": "2", "answer[1][ans_id]": "26"], ["answer[2][ans_id]": "36", "answer[2][question_id]": "5"], ["answer[3][ans_id]": "40", "answer[3][question_id]": "6"], ["answer[4][question_id]": "7", "answer[4][ans_id]": "41"], ["answer[5][question_id]": "8", "answer[5][ans_id]": "46"], ["answer[6][ans_id]": "49", "answer[6][question_id]": "9"], ["answer[7][question_id]": "10", "answer[7][ans_id]": "54"], ["answer[8][question_id]": "11", "answer[8][ans_id]": "57"]

如何获得理想的输出?

2 个答案:

答案 0 :(得分:1)

我不会回答您的要求,因为这对我来说似乎不是很方便的解决方案。

您应该避免使用将来很难管理的复杂字典结构。您可以根据自己的要求使用structclass来轻松易读。

由于我不知道您正在使用的实际结构,因此仅作为示例 例如

struct  Question {

   var questionID:String?
   var question:String?
   var answersOption:[Options]?

   var correctAnswer:Options?{
       return self.answersOption.filter{$0.isCorrectAnswer == true}
   } 


}

struct Options {
   var answerID:String?
   var answer:String?
   var isCorrectAnswer = false
}

现在,您可以创建问题数组,并且在其中有选项以及正确答案;不错吧

希望对您有帮助

答案 1 :(得分:-1)

您可以通过这种方式获取所有值-

for i in 0 ..< params.count
{
     print(params[i] , terminator:",")
}