SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

False positive for `prefer_self_in_static_references` when an inner struct has the same name as its owner

Open mildm8nnered opened this issue 1 year ago • 5 comments

New Issue Checklist

Bug Description

struct S1 {
    struct S1 {}
    var s = S1()
}

prefer_self_in_static_references will report a violation at var s = S1(), but S1 here refers to the inner struct, not the outer one, so var s= Self() would be different, and would fail if the inner S1 has different properties to the outer one.

As a workaround,

struct S1 {
    struct S1 {}
    var s = Self.S1()
}

Has the same effect, but does not trigger prefer_self_in_static_references.

mildm8nnered avatar Dec 27 '24 15:12 mildm8nnered

I couldn't see any easy way to fix this :-(

mildm8nnered avatar Dec 27 '24 15:12 mildm8nnered

Would Self not refer to the inner struct?

Edit: Seems like the compiler wouldn't even allow it: https://swiftfiddle.com/iclkmj5lbbd4xew7g42r7l4vo4

SimplyDanny avatar Dec 27 '24 15:12 SimplyDanny

Would Self not refer to the inner struct?

Edit: Seems like the compiler wouldn't even allow it: https://swiftfiddle.com/iclkmj5lbbd4xew7g42r7l4vo4

🤦 - I messed up with my example - corrected above.

Here is an example that shows it more clearly I hope

struct Foo {
  struct Foo {
    var bar = 0
  }
  var foo = 0

  func something() -> Int {
    Foo().bar
  }
}

This compiles fine, but

swiftlint --only-rule prefer_self_in_static_references t.swift produces

warning: Prefer Self in Static References Violation: Use Self to refer to the surrounding type name (prefer_self_in_static_references)

mildm8nnered avatar Dec 29 '24 12:12 mildm8nnered

Got it. ~This is nothing we can reliably avoid due to missing type information.~

SimplyDanny avatar Dec 29 '24 18:12 SimplyDanny

Opened #6552 to skip this rule when a nested type shadows the enclosing type name, and added an example to lock the case in.

theamodhshetty avatar Mar 25 '26 02:03 theamodhshetty