0

I have a following code

struct Cat{
    var itter = 0
}

class CatStorage{
    var items = Array<Cat>()
    {
        didSet{
            print(items)
        }
    }
}

var store = CatStorage()
store.items.append(Cat())

for var cat in store.items {
    cat.itter += 1 // won't trigger didSet of CatStorage
}
store.items[0].itter += 1  // will trigger didSet of CatStorage

And I can't figure out, why

for var cat in store.items {
    cat.itter += 1 // won't trigger didSet of CatStorage
}

doesn't trigger didSet of CatStorage class? I guess it's because of the fact that Cat is a struct and struct is a value type in Swift, but at the same time I'm iterating over values inside a class, which is a reference type, so that's why I can't figure out why does it works this way. And I'm became more puzzled, when I saw that

store.items[0].itter += 1  // will trigger didSet of CatStorage

actually triggers didSet of CatStorage class. Can you please help me to understand why does it works that way? And how can I iterate over items inside CatStorage so that didSet called on change?

Plato
  • 95
  • 1
  • 5
  • 3
    you're creating a copy of the cat in the `var cat` of the for loop – Clashsoft Jul 01 '20 at 10:13
  • 1
    Oh, I see now. So for the `iterate over items inside CatStorage so that didSet called on change` I would have to use `enumerated` and `store.items[0].itter += 1`. Thank you – Plato Jul 01 '20 at 10:19
  • Hi, didSet will work after you adding to property any Array. It doesn't work with appending item to existing array. – Oleksandr Vaker Jul 01 '20 at 10:30
  • See [How to mutate a struct object when iterating over it](https://stackoverflow.com/questions/29777891/swift-how-to-mutate-a-struct-object-when-iterating-over-it) – pawello2222 Jul 01 '20 at 10:58

0 Answers0