-1

I have a lazy var in my struct called labelColors:

lazy var _labelColors: LabelType = { return url.getTagColors() }()
    
    var labelColors  : LabelType {
        mutating get { return _labelColors }
                 set { _labelColors = newValue }
    }

It should only call its value, when it is really needed the first time. When using a filter on my huge array, I have

let redFilesOnly = files.filter({ $0.labelColors.isColorSet(color: TagColors.red) })

But error is "Cannot use mutating getter on immutable value: '$0' is immutable". But how can I use a getter function, which is defined as lazy, so it will be changing its value?

Peter71
  • 2,180
  • 4
  • 20
  • 33

1 Answers1

1

The problem its not about the structure or lazy definition. In that line files.filter({ $0.labelColors.isColorSet(color: TagColors.red) }) , iteration with structure , you have a let variable ($0 is a let here) and let constant can not be modified as you know , so you are getting this error message. To fix that use :

let redFilesOnly = files.filter({ val in
     var new = val
     return new.labelColors.isColorSet(color: TagColors.red) 

})
Omer Tekbiyik
  • 4,255
  • 1
  • 15
  • 27
  • How is this not a duplicate? – Joakim Danielson Apr 12 '23 at 08:03
  • the page was open for a long time. I didn't see your answer :) I just wrote an extra explanation so I kept the answer @JoakimDanielson – Omer Tekbiyik Apr 12 '23 at 08:04
  • 1
    It's still a duplicate. – Joakim Danielson Apr 12 '23 at 08:07
  • Just for understanding: the value is copied to "new" and then the property of new is updated by lazy function. So the original ($0) is still untouched? – Peter71 Apr 12 '23 at 08:41
  • $0 is untouched yes but when you return operation with 'new' the property redFilesOnly affected – Omer Tekbiyik Apr 12 '23 at 08:48
  • Ok, but my intention was that the lazy var is initialized, when needed. So here it will call the time consuming initializer more than once. The main data in files should be updated, to be faster when called a second time using the already read data from lazy var. – Peter71 Apr 12 '23 at 08:55
  • @JoakimDanielson There's no rule against duplicate answers to the same question. This one is actually slightly better than yours because it includes some explanation. – JeremyP Apr 12 '23 at 08:58
  • @Peter71 There is no way to set the property inside a `struct` from inside the `filter` closure to which it has been passed as a parameter because of the value semantics. Even `$0` is not the same struct as the one inside `files`. – JeremyP Apr 12 '23 at 09:01
  • OK, that's what I want to know, if I miss something. So I need a totally other solution that using a lazy var. Thanks! – Peter71 Apr 12 '23 at 09:58