ios - indexPath 不可变? swift

标签 ios swift indexing uiviewcontroller segue

我正在尝试增加我的 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/

相关文章:

sql-server-2005 - 如何解决 SQL Server 2005 中数据类型为 varchar(4096) 的列上的 900 键长度限制索引?

ios - SKTileMapNode:检测触摸的 Tile?

ios - 在游戏结束场景中使用 View Controller

ios - 无法从另一个 TableView 加载另一个 TableView

ios - SwiftUI:警报自动关闭(当它不应该时!)

Swift:通过索引访问字典

python - 以与使用元组相同的方式使用 ndarray 进行索引

iphone - 使用浏览器我想打开一个网址,用于付款

swift - 将对象属性分配为另一个对象的函数的输入参数

ios - 如何在 NSMutableArray 中快速将对象添加为 NSMutableArray