indexPath不可变吗?迅速

时间:2017-01-11 08:28:39

标签: ios swift indexing uiviewcontroller segue

我尝试使用

增加indexPath
selectedPrevious = mons[indexPath -= 1]

但我收到错误声明 indexPath是一个让常量。似乎没有办法将它改为变量。我尝试过创建和Int变量并将其分配给索引,如此

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

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

  

无法下标类型的值' [怪物]'索引类型为'()'

如何增加此值。目的是在我的第二个Viewcontroller中重新加载数据。仅仅通过index变量本身不会影响数据重新加载。

1 个答案:

答案 0 :(得分:3)

默认情况下,传递给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