我有在 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数据中获取值“奖品”,而数量 answerList 对象并不总是与 QuestionList 相同。
我需要将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}]
最佳答案
我建议两个答案:
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]
关于arrays - Swift 从具有不同索引的其他字典数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53515764/