Yes.
For static constants, I canât think of a counterexample right now. So (tentatively) nothing against it. But for static vars? The potential for unexpected side effects is huge, as one may be inadvertently modifying a value used in all instances of the type (instead of just for the specific instance at hand). Or worse, for other users of the MyButton type. Imagine the very leading example of this thread, using a static var:
struct MyButton: View {
static var height: CGFloat = 44
var body: some View {
// ...
.frame(height: Self.height)
}
}
If Self was not required, one could do something like:
func expandHeight() {
height = 128
}
Now, is this changing height for this instance of MyButton? Or is this changing a property of the MyButton type, that will change the height value used by all buttons? One would need to go look up the definition of height and see whether itâs static or not. That's the kind of local reasoning that would be impeded if the Self was dropped.
In current Swift, height in the snippet above could be:
- A local variable (but we can readily see it's not defined within the scope of
expandHeight(), so it's not that in this case).
- An instance variable of the enclosing
struct/class.
- A global property.
Ignoring global properties for a second here, we know that the effects of modifying height are limited to either the local scope or the specific instance of the enclosing object. If naked accesses to static properties were to be allowed, the potential effects could cause long distance effects, as we'd need to consider a fourth option:
- A
static property of the enclosing struct/class.
Global functions and properties already have this issue, and are not required to be prefixed by anything to make that explicit. However, I think global functions/variables are known to be dangerous if used wrong, so in my experience they are given a lot more thought when being written (and there's few of them in a typical codebase). I don't think that's true for static properties and functions, particularly not those used for UI like the example above.
I realize that in this particular made-up scenario, if height needs to be mutable, most developers would choose to use an instance property rather than a static var. But static vars do exist and are used (for different reasons), and being able to modify their values without realizing that the property is not an instance property could unexpectedly make changes far outside the bounds of the instance.
Seems like two of the three points would be solved if the language supported let x: C { C() } (or any other way of creating non-stored constants that the compiler is guaranteed to inline for callers).