4 ms·
Or maybe they just opt for it for the simplicity sake? Just like said above, the first is just a magic getter which is a function underneath anyway.
by romanovcode 7y ago
Or maybe they just opt for it for the simplicity sake? Just like said above, the first is just a magic getter which is a function underneath anyway.
- skohan 7y agoBut why should I as the user of an interface care whether something is implemented as a function or whether it's just a reference to a pure value? For instance, let's imagine in some C++-like language I had two list implementations: one static and one dynamic: class StaticList { ... int count; // set at initialization time } class DynamicList { ... int count() { ... // compute the count dynamically return count; } } Here `count` is conceptually the same between these two implementations, but if I want to get that value, I have to access it differently: int c1 = staticList.count; int c2 = dynamicList.count(); But that difference is essentially an implementation detail which means nothing to the client. The Swift way just lets me express my interface however I decide is most fitting.
- dbaupp 7y agoThere is a useful distinction between "properties" and "functions" that appears in some languages: properties exist in memory and so can be addressed. This is particularly important for "systems"/low-level programming, where addresses are often manipulated directly and need to be stable/controlled. In languages like C, C++ and Rust, properties are things that are definitely in memory, and functions/methods are things that may not be. If you have an interface like `count` that may be dynamic, it should be uniformly expressed as a method/function (that may have a trivial "return count;" implementation). On the other, Swift has to put a non-trivial amount of infrastructure into making sure all the things with property syntax can behave as if they are backed by memory, so that an address/pointer can be generated for them (in the general case, a temporary pointer, that becomes invalid quickly).
- kibwen 7y agoThe reason that performance-oriented languages like C++ and Rust make a distinction there is to make it easier for someone reading the code to understand the performance implications of a piece of code. Accessing a field involves jumping to a statically-known offset, which is a minor and predictable cost, whereas calling a function could have any cost imaginable. It's reasonable for languages that prioritize ergonomics over extreme performance to make the decision to paper over that distinction.