更改结构的值无效

Changing value of a struct has no effect

我的 UICollectionView 具有以下模型:

class MainVCModel {

    let models = [
        CellModel.init(UIImage.init(named: "1.jpg")!),
        CellModel.init(UIImage.init(named: "2.jpg")!),
        CellModel.init(UIImage.init(named: "3.jpg")!),
        CellModel.init(UIImage.init(named: "4.jpg")!),
        CellModel.init(UIImage.init(named: "5.jpg")!),
        CellModel.init(UIImage.init(named: "6.jpg")!),
        CellModel.init(UIImage.init(named: "7.jpg")!),
        CellModel.init(UIImage.init(named: "8.jpg")!),
        CellModel.init(UIImage.init(named: "9.jpg")!),
    ]
}

struct CellModel {
    var isEnlarged: Bool = false
    var image: UIImage

    lazy var rotatedImage: UIImage = self.image.rotate(radians: Float(Helper.degreesToRadians(degrees: 6)))!

    init(_ image: UIImage){
        self.image = image
    }
}

在我的 CollectionViewController class 我有:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var currentModel = model.models[indexPath.row]
        if !currentModel.isEnlarged {
            print("should enlarge")
            currentModel.isEnlarged = true
            enlargeOnSelection(indexPath)
        }   else {
            print("should restore")
            currentModel.isEnlarged = false
            restoreOnSelection(indexPath)
        }
    }

但是当我设置 currentModel.isEnlarged = true 它没有任何效果,它实际上存储了 false 值,我在调试时注意到了这一点。为什么?

这一行:

var currentModel = model.models[indexPath.row]

如果models是结构数组,currentModel是一个副本,所以设置currentModel的属性不会影响数组中的任何内容。

您必须将代码更新为此,因为您将新值保存在主模型的副本中。

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var currentModel = model.models[indexPath.row]
        if !currentModel.isEnlarged {
            print("should enlarge")
            model.models[indexPath.row].isEnlarged = true
            enlargeOnSelection(indexPath)
        }   else {
            print("should restore")
            model.models[indexPath.row].isEnlarged = false
            restoreOnSelection(indexPath)
        }
    }

更改值后,您需要更新数组。由于结构是按值传递而不是引用。

currentModel = model.models[indexPath.row]
currentModel.isEnlarged = true
model.models[indexPath.row] = currentModel

添加前请注意检查索引是否可用。