user2373192
user2373192

Reputation: 31

Swift get value from other array of dictionary with different index

I have list of question that i present in CollectionView, with number of items based on number of questionList data like this

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.questionList.count
}

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   //present the cell
}

And in in my cell i want to get the value "prize" from answerList data, while number of answerList object not always the same like questionList.

I need to map the index key in questionList with index in answerList, so for example i can present if title="Question2", the prize is 2000 because its the same value in key index. How I do that?

This is my example data:

questionList":[{"index":0,"title":"Question 1"}, 
{"index":1,"title":"Question 2"}, 
 {"index":2,"title":"Question 3"]

"answerList": [{"index":1,"prize":2000}
,{"index":2,"prize":5000}]

Upvotes: 0

Views: 248

Answers (3)

DungeonDev
DungeonDev

Reputation: 1226

Your models will be something like:

    struct Question: Codable {
        var index: Int
        var title: String
    }

    struct Answer: Codable {
        var index: Int
        var price: String
    }

and the code:

    var answers: [Answer]?

    var question = Question(index: 0, title: "Question1")
    if let answers = answers, let chosenOne = (answers.filter{$0.index == question.index}).first {
        print(chosenOne.price)
    }

Upvotes: 0

Celina
Celina

Reputation: 623

I'm not a swift pro, but I would start with a filter method like this in the func collectionView:

func filter(indexOfQuestionlist: IndexPath){
    answerlist.filter {$0.index == indexOfQuestionlist}
}

and your data looks like json, so I guess you are converting it somehow to Swift Objects, via serialization or Codable?

Upvotes: 0

Tal Cohen
Tal Cohen

Reputation: 1457

I suggest two answers:

1) find the right answer by the index value.

for example on the first question cell:

let question = {"index": 0, "title": "Question 1"}
let index = question["index"]

if let answerIndex = answerList.index { $0[index] == index } {
    let answer = answerList[index]
}

2) nest answer inside the question so your data will be like the following:

let questionList = [{"index":0, "title":"Question 1"}, 
{"index":1, "title": "Question 2", "prize": 2000}, 
{"index":2, "title": "Question 3", "prize": 5000]

Upvotes: 0

Related Questions