arrays - Swift 从具有不同索引的其他字典数组中获取值

标签 arrays swift mapping

我有在 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/

相关文章:

elasticsearch - 关键字的Elasticsearch映射

java - 你什么时候在 RxJava 中使用 map 和 flatMap?

Java二维数组定义

ios - WKWebView - 如何获取我们刚刚触摸的输入类型的属性

ios - 将图像插入 PDF 文件 Swift

ios - 在 swift 中使用 ACEAutocompleteBar 崩溃 :

android - Flutter Pub : Expected a key while parsing a block mapping. 路径:

ios - 按索引移动数组中的元素

c - 找出我的数组中有多少个正数

python - 在 numpy 数组中将特定值设置为零