我正在尝试增加我的 indexPath 使用
selectedPrevious = mons[indexPath -= 1]
但我得到的错误是indexPath is a let constant。但是似乎没有办法将其更改为变量。我试过像这样创建 Int 变量并将其分配给索引
index = indexPath.row -= 1
selectedPrevious = mons[index]
但是现在,尝试使用 +=
或 -=
会产生新的错误。
Cannot subscript a value of type '[Monster]' with an index of type '()'
我怎样才能增加这个。预期目的是在我的第二个 Viewcontroller
中重新加载数据。仅传递 index
变量本身不会影响数据重新加载。
最佳答案
传递给 swift 函数(按值传递)的参数(arguments)默认为 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
关于ios - indexPath 不可变? swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41585960/