我有我在CollectionView中显示的问题列表,其项目数基于诸如此类的questionList数据的数量
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.questionList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//present the cell
}
在我的单元格中,我想从answerList数据中获取值“ prize”,而 answerList对象并不总是与问题列表相同。
我需要将questionList中的索引键与answerList中的索引进行映射,因此例如,如果title =“ Question2”,由于键索引中的值相同,我可以给出2000。我该怎么做?
这是我的示例数据:
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}]
答案 0 :(得分:0)
我建议两个答案:
1)通过索引值找到正确的答案。
例如在第一个问题单元格上:
let question = {"index": 0, "title": "Question 1"}
let index = question["index"]
if let answerIndex = answerList.index { $0[index] == index } {
let answer = answerList[index]
}
2)将答案嵌套在问题内,这样您的数据将如下所示:
let questionList = [{"index":0, "title":"Question 1"},
{"index":1, "title": "Question 2", "prize": 2000},
{"index":2, "title": "Question 3", "prize": 5000]
答案 1 :(得分:0)
您的模型将类似于:
struct Question: Codable {
var index: Int
var title: String
}
struct Answer: Codable {
var index: Int
var price: String
}
和代码:
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)
}
答案 2 :(得分:0)
我不是一个敏捷的专业人士,但我将在func collectionView
中以这样的过滤器方法开始:
func filter(indexOfQuestionlist: IndexPath){
answerlist.filter {$0.index == indexOfQuestionlist}
}
并且您的数据看起来像json,所以我想您正在通过序列化或Codable将其转换为Swift Objects?