Skip to content

prefer_self_in_static_references rewrites is/as type operands to Self, silently changing runtime behavior #6764

Closed

Description

@Brett-Best

New Issue Checklist

Describe the bug

prefer_self_in_static_references (opt-in) rewrites a reference to the enclosing type into Self. Inside a class (or extension on a class), it also rewrites the type operand of an is / as? / as! cast. Because Self is the dynamic type, this is not equivalent to the named static type for a non-final class, so the autocorrection silently changes runtime behavior (the code still compiles).

The rule already recognizes this hazard for X.self (it skips X.self in class-like scopes), but is/as cast operands are an inconsistent gap.

Complete output when running SwiftLint

Given:

class A {}
class B: A {}

extension A {
    func isA(_ x: Any) -> Bool { x is A }
}

.swiftlint.yml:

only_rules:
  - prefer_self_in_static_references

swiftlint lint --fix rewrites the body to x is Self. But:

B().isA(A())   // before fix: `x is A`    -> true
               // after fix:  `x is Self`  -> false   (Self == B, and an A() is not a B)

The same happens for as? / as! (a as? A -> a as? Self) and for existential metatypes via .Type in a protocol extension (x is A.Type -> x is Self.Type flips results, since Self.Type is the conforming concrete metatype, not the existential metatype).

Expected behavior

In a class-like scope, the rule should not rewrite the type operand of is / as? / as! (nor a .Type metatype used in such an operand) to Self, mirroring the existing X.self skip — because Self (dynamic type) is not interchangeable with the named static type there. Static member references (A.staticMethod() -> Self.staticMethod()) should keep being corrected as today.

Environment

Activity

  1. added
    bug
    on Jun 8, 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