[swift-evolution] [proposal] Allow "let" for computed properties which only reference immutable data

Haravikk swift-evolution at haravikk.me
Wed May 11 16:21:05 CDT 2016

> On 11 May 2016, at 21:04, Chris Lattner <clattner at apple.com> wrote:
> On May 11, 2016, at 11:31 AM, Joe Groff via swift-evolution <swift-evolution at swift.org> wrote:
>>>   var combined:[Int64] { return a + b }
>>> }
>>> Each of these arrays is 512kb, so storing a fixed value for the combined property would require another megabyte of space per instance of Test, but if the combined property is only infrequently called on some instances of Test, then it would be a waste of memory to precompute it, especially if you’re dealing with thousands of instances, with only a fraction of them calling the computed property. If you want to accelerate usage of the computed property then that’s what lazy variables are for, as you can delay the expensive combination until you actually need it.
>> Being constant doesn't need to imply "precomputed". I would expect a computed 'let' to still be computed on-demand. 'let' is more important as an API contract; you're guaranteeing to the user that an API won't produce different values if called on the same object at different times.
> Right.  “let” means “always has the same value”, a get-only property means “can not be set” (which is less restrictive).  Computed or not isn’t the issue here.

Ah, thanks both of you, I misunderstood then.

Hmm, in that case though, other than the simple case given in the original message, it seems like this might be non-trivial to check, as you’d need to trace every method that could be used within the computed property to ensure that no vars are ever accessed.

I proposed a while ago the idea of having the compiler determine whether a method is mutating automatically, as this could do various useful things like issue a warning if a mutating method that doesn’t change anything and similar cases, but it was dismissed at the time due to the complexity of adding such checking. This seems like it might be similar in principle; it seems very reasonable in a self-contained method that doesn’t rely on any others, but the rest of the time it’s hard to check.

I suppose it could be done for these kinds of self-contained computed properties initially though?

More information about the swift-evolution mailing list