Why does Swift have the concepts of "lazy variables" and "computed properties", when it seems that simple methods or functions would be appropriate for the purpose?
In the time-consuming case of computing Pi, shouldn't this have been a method instead? And the same in this case. Why force something to be a variable/property that clearly is more complex?
Answer: Lazy variables exist to cut on loading time (i.e. for optimization reasons). Some variables aren't needed immediately unless explicitly called for. And they, like Math.pi
might take a while to compute. So the application may start computing them in a background thread when the most important user-initiated operations have finished.
As for computed properties, I think it's more of a language decision. Objective-C introduced properties a long time ago, and they've always been technically 'computed' (with getters and setters, be it automatically synthesized / explicitly implemented), and it was (and is) a wildly accepted feature. Why? I don't know for sure. Maybe there isn't 'one clear answer' to this question. Like I said, I believe it's a language decision, not something that can be rationalized completely.
For me personally, it feels more intuitive to both read and write a property using the same .property
syntax, rather than property()
and setProperty(_: Property)
functions. This is an abstraction, and language abstractions exist for comfort / ease-of-use. Your examples are highly contrived, and computed properties are used by the thousands across Apple's frameworks. Not each computed property needs to be extremely time consuming, and most of them are in fact practically instant; thus they are abstracted to feel so.
When you think about it, everything is technically computed. Even if you, for example, set an integer value directly to a structure field, there are things that need to happen on a lower scale. These low level computations are abstracted to feel like non-computed, concrete entities, when in reality they are. It all boils down to abstraction.