Skip to content

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

Closed

Description

@mildm8nnered

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.

Activity

  1. added
    bug
    on Dec 27, 2024
  2. mildm8nnered commented on Dec 27, 2024

    @mildm8nnered
    CollaboratorAuthor

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

  3. SimplyDanny commented on Dec 27, 2024

    @SimplyDanny
    Collaborator

    Would Self not refer to the inner struct?

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

  4. mildm8nnered commented on Dec 29, 2024

    @mildm8nnered
    CollaboratorAuthor

    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)

  5. SimplyDanny commented on Dec 29, 2024

    @SimplyDanny
    Collaborator

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

  6. added
    acceptable-false-positive
    on Dec 29, 2024
  7. theamodhshetty commented on Mar 25, 2026

    @theamodhshetty
    Contributor

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

  8. removed
    acceptable-false-positive
    on Apr 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions