I'm learning Swift and I'm facing a problem in one of my model classes. What I'm trying to do is having a lazy-loaded property that can be "invalidated" when the data it is based on changes. (something like this: https://stackoverflow.com/a/25954243/2382892)
What I have now is something like this:
class DataSet {
var entries: [Entry]
var average: Double? {
return self.entries.average
}
}
Array<Entry>.average
computes the average of a property of Entry
, but returns nil if the array is empty.
Since this average could potentially be expensive to compute, I'd like to do that lazily and store a cached value of it and recalculate it only if necessary (when DataSet.entries
is modified).
Now, following this answer, I should do something like this:
class DataSet {
var entries: [Entry]
var _average: Double?
var average: Double? {
if _average == nil {
_average = self.entries.average
}
return _average
}
}
However I have the problem of handling both the case that the average is to be recomputed, and when the array is empty and there's no meaningful average to return.
Since I know the average value will always be positive, I could use a default value (such as -1.0) to indicate the cache is no more valid, and nil
to mean there are no entries, or vice-versa (nil
means the average has to be computed again; -1.0 when there are no entries).
This however doesn't seem elegant, or the "Swift way" to achieve this behavior (or is it indeed?).
What should I do?