0

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?

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

3 Answers3

2

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    Might want to read my answer here: https://stackoverflow.com/a/27366050/341994 And my book http://www.apeth.com/swiftBook/ch04.html#SECreferenceTypes – matt Apr 11 '19 at 20:09
1

You have to update your code to this as you are saving the new value in a copy of you main model.

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)
        }
    }
Razi Tiwana
  • 1,425
  • 2
  • 13
  • 16
1

after changing the value you need to update your array. Since struct is Pass by Value not reference .

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

Be careful to check index is available before adding.

Digs
  • 193
  • 1
  • 11