Why is it that you can't implicitly reference static methods/properties within instance methods in Swift?

I understand the argument that it clarifies the source of the variable to be from the class for example, but if that is the case, then why does swift allow and actively encourage omitting self for instance members? As far as I know, static methods/properties in Swift can't be overwritten either, removing any ambiguity for subclasses with only those being shadowed needing to directly refer to the type like how self is used to refer directly to instance members. Plenty of other languages allow this, and sometimes type names can get rather long making this real pain point in some instances where a simple static method call is made far more verbose than feels necessary.

1 Like

You can do this:

class AVeryLongClassNameThatTakesALongTimeToType {
  static func staticFunction() {}
  func instanceFunction() {
    Self.staticFunction()
  }
}

By the way, the compiler also emits a fix-it when if you simply do staticFunction() which will automatically add the AVeryLongClassNameThatTakesALongTimeToType prefix, so you don't have to type it out manually.

2 Likes

Still used to Swift 4.2, so I didn't even know Self was legal syntax here to refer to the type and misread it! this certainly helps a lot in cutting down redundant typing.

I am not sure what you mean - here, we're just replacing the explicit type name with Self shorthand. There's no boilerplate.

1 Like