Search code examples
swiftfilterlazy-evaluationmutable

Avoid "$0' is immutable" on a lazy getter function?


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?


Solution

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