arrays - Swift 错误 - 对成员 'subscript' 的引用不明确

标签 arrays swift

我有一个名为 comcomingTransactions 的双数组。

var upcomingTransactions: [[Transaction]]

但是当我试图从它到达我的单元格时,我在

for (j, _) in upcomingTransactions[i] {

我想要的只是从每个部分中检索单元格。我用我的 var 检索部分,但是当我尝试使用第二个 var j 捕获单元格时,我需要放一些东西,但我看不到什么。这是我的代码:

var indexPaths: [IndexPath] = []
for i in 0..<upcomingTransactions.count {
    for (j, _) in upcomingTransactions[i] {
        indexPaths.append(IndexPath(row: j, section: i))
    }
}

最佳答案

您的for-each 迭代将导致ij(假设我们修复了编译错误)为Transaction 实例,因为 for-each 遍历数组中的值。如果你想要索引,你有两个选择:

  1. 使用 enumerated(),它还会为您提供索引:

    var indexPaths: [IndexPath] = []
    for (i, arr) in upcomingTransactions.enumerated() {
        for (j, _) in arr.enumerated() {
            indexPaths.append(IndexPath(item: j, section: i))
        }
    }
    
  2. 映射索引:

    let indexPaths = upcomingTransactions.enumerated().flatMap { (i, arr) in
       (0..<arr.count).map { j in 
           IndexPath(item: j, section: i) 
        }
    }
    

第二种方法更实用,而第一种更命令。我个人推荐功能性的,因为它只使用不可变的实体。

关于arrays - Swift 错误 - 对成员 'subscript' 的引用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48889413/

相关文章:

PHP:获取以逗号分隔的文本

swift - Realm.asyncOpen 不打开 Realm

arrays - 通过结构和数组填充 Tableview

c# - 如何用字符串索引声明字符串数组?

swift - 从字典计算小计和总计

swift - tableView header 不更新数据 Swift

ios - 如何使用解析保持当前用户 session 处于事件状态?

ios - 在 'NSURL item' 中查找 'NSURL array' 的索引

php - 从 mysql 获取数组创建命名 session 数组

java - 解析没有键的Json数组