[swift-users] Why can't Swift instance methods call class methods without qualification?
dan at lionheartsw.com
Fri Jul 1 12:20:26 CDT 2016
On Fri, Jul 1, 2016 at 11:58 AM, Jens Alfke via swift-users
<swift-users at swift.org> wrote:
> > On Jul 1, 2016, at 9:38 AM, zh ao <owenzx at gmail.com> wrote:
> > Swift forces you to use class name to alert you on the fact that static variables and methods (may) affect the other instances of the class as static variables are shared between instances. That does make sense.
> I disagree. Both static and instance methods can affect other instances of the class. In other words, just looking at these two calls:
> there’s no way to tell whether either or both of them change class-wide state. (To spell it out clearly: the implementation of the instance method something() might change the variable MyClass.staticState.)
> I think the reasoning behind this syntax is simply to make it easy to distinguish usages of static members (methods or variables) from instance ones.
I agree. If not for this rule, the compiler would need to enforce
uniqueness across type and instance method names. There’s no other way
to disambiguate which function you’re trying to call.
Also, keep in mind that something() is syntactic sugar for
self.something(), which itself is syntactic sugar for
If the compiler allowed you to skip MyClass and let you use
something() to reference the type method, how can it know that you
mean MyClass.something() and not MyClass.something(self)()? Since both
functions accept different parameters this behavior would be undefined
and you would be unable to use the same name for a type method and
instance method on the same type.
More information about the swift-users