iosswiftswift-structs

Changing value of a struct has no effect


I have UICollectionView that have a model with following:

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
    }
}

In my CollectionViewController class i have:

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)
        }
    }

But when i set currentModel.isEnlarged = true it has no effect, it actually store false value, which i notice when debugging. Why?


Solution

  • In this line:

    var currentModel = model.models[indexPath.row]
    

    If models is an array of a struct, currentModel is a copy, so setting a property of currentModel does not affect anything in the array.