Omegaman Omegaman - 6 months ago 17
Swift Question

Can a swift computed property getter mutate a structure?

I have a struct wrapping a

var data:[T]
that also supplies some statistics on the internal Array. One statistic is the max value, which can be an expensive operation because it requires searching the every element to determine the max value-- so I'd like to cache the max value and only recalculate it if I need to:

private mutating func getMax()->T? {
if let m=maxValue {
return m
else if data.count>0 {
return maxValue
else {
return nil

That seems to work fine as a method, but I can't figure out how to do the same thing as a computed property.

var max:T? {return getMax()}

leads to a complaint that the accessor needs to be marked "mutating" because getMax() is mutating (actually I'd put the getMax code into the property accessor, but it's easier to not rewrite the code here).

Xcode suggests I rewrite the code thusly:

var max:T? mutating {return getMax()}

which then flags another problem and Xcode suggests putting a semicolon before mutating which leads to a suggestion to put another semicolon after mutating and then yet another semicolon after mutating and it's clear the compiler isn't even trying to help but just has a semicolon fetish.

Is there a way to write a computed property that permits caching values or am I stuck writing this as a method?


The correct syntax, despite the compiler's suggestions, would be:

var max:T? {
    mutating get {return getMax()}