Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

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?

Upvotes: 0

Views: 70

Answers (3)

Digs
Digs

Reputation: 193

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.

Upvotes: 1

Razi Tiwana
Razi Tiwana

Reputation: 1435

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

Upvotes: 1

matt
matt

Reputation: 534950

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.

Upvotes: 2

Related Questions