【问题标题】:indexPath not mutable? SwiftindexPath 不可变?迅速
【发布时间】:2017-01-11 08:28:38
【问题描述】:

我正在尝试使用

来增加我的 indexPath
selectedPrevious = mons[indexPath -= 1]

但我收到错误消息,指出 indexPath 是一个 let 常量。但是,似乎没有办法将其更改为变量。我尝试过创建和 Int 变量并将其分配给索引,就像这样

index = indexPath.row -= 1
selectedPrevious = mons[index]

但现在,尝试使用 +=-= 会出现新错误。

不能用“()”类型的索引为“[Monster]”类型的值下标

我怎样才能增加这个。预期目的是在我的第二个Viewcontroller 中重新加载数据。仅传递 index 变量本身不会影响数据重新加载。

【问题讨论】:

  • 你想要let index = indexPath.row - 1,或者只是selectedPrevious = mons[indexPath.row - 1]
  • 问题是当我调用它然后重新加载数据时,它只调用一次,这就是我试图增加它的原因。
  • 如果你想增加 indexpath.row 只是增加 numberofrow 方法的返回行数而不是 indexpath.row 。

标签: ios swift indexing uiviewcontroller segue


【解决方案1】:

传递给 swift 函数(按值传递)的参数(参数)默认为let。这意味着您可以读取传递给函数的参数值但不能修改。

这适用于所有变量,而不仅仅是 indexPath :)

所以你做错了:)如果你想修改 indexPath 的值,你可以这样做:)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath)
        var copiedIndexPath = indexPath
        copiedIndexPath.row = copiedIndexPath.row + 1
}

如您所见,我创建了索引路径的本地副本并修改了它的值:)

编辑:

声明

indexPath.row -= 1

不仅会将 indexPath 的行减一,还会尝试将数据分配回默认情况下允许的 indexPath。如果你真的想修改 indexPath 值本身,你可以按照我上面提到的那样做。

如果您的意图只是计算行索引而不是自行修改 indexPath

index = indexPath.row - 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2015-12-04
    • 2019-12-18
    相关资源
    最近更新 更多