Ios 更改数组中的值

Ios 更改数组中的值,ios,swift,collectionview,Ios,Swift,Collectionview,选择自定义单元格后,项目为Bool值应从true更改为false,反之亦然。通过使用UICollectionViewDelegate协议中的didSelectItemAt方法,您可以知道何时选择了单元格 这就是老师要求我们做的 override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var item = shoppingLis

选择自定义单元格后,项目为
Bool
值应从true更改为false,反之亦然。通过使用
UICollectionViewDelegate
协议中的
didSelectItemAt
方法,您可以知道何时选择了单元格

这就是老师要求我们做的

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        var item = shoppingListController.shoppingItems[indexPath.item]

        item.itemHasBeenAdded = true
}

这就是我目前所拥有的。

您可以编写代码,在选择后将布尔值更改为相反的值,如下所示:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        var item = shoppingListController.shoppingItems[indexPath.item]

        item.itemHasBeenAdded = !item.itemHasBeenAdded
}
编辑:正如《梦的艺术》所说,此代码将产生相同的效果:

item.itemHasBeenAdded.toggle()

注意这种模式:

var item = shoppingListController.shoppingItems[indexPath.item]
item.itemHasBeenAdded = true
如果数组中的项是引用类型(即
),则该操作将有效,因为
将引用数组中的实例。但如果它是值类型(即
结构
),则此本地
变量最终将成为对象的副本,并且您将更改此副本中的
项已添加
,而不更新数组中的项

如果它是一个
结构
,理论上可以将该项复制回来,例如

var item = shoppingListController.shoppingItems[indexPath.item]
item.itemHasBeenAdded.toggle()
shoppingListController.shoppingItems[indexPath.item] = item
注意,你说过你想“从真变假,反之亦然”。在本例中,我使用
切换
来回切换

或者,更简单的方法是直接更新数组中的项,无论它是引用类型还是值类型,都会起作用,例如

shoppingListController.shoppingItems[indexPath.item].itemHasBeenAdded.toggle()

不用说,这个关于本地
变量的警告仅适用于数组中的项本身是值类型(a
结构
)的情况。如果是
,则无论哪种方式都可以。但是您仍然需要使用
toggle
让这个方法来回切换
Bool

Bool类型有方法
toggle
,因此可以只编写
项。项已添加。toggle()