Swiftlint Rule: Project Prefix on top-level types

47 views Asked by At

Is there a way to add a rule in swiftlint that will enforce every top level class, enum, struct or protocol starting with a predetermined prefix?

In my case the prefix is PSO, so all my top type definitions should be PSOMyClass PSOMyStruct, etc...

I've tried creating a custom rule like this:

custom_rules:
  pso_prefix_rule:
    name: "PSO Prefix Rule"
    regex: '^(class|struct|enum|protocol) (?!(PSO))'
    message: "Top-level classes, structs, enums, and protocols should start with a 'PSO' prefix."
    severity: warning

The issue of doing it like this, is that any keyword before class, struct etc will exclude it from the rule, for example:

  • Not Triggered private class MyClass @Model struct MyStruct

  • Triggered class MyClass struct MyStruct

If I instead change the regex starting with ^ to a \b:

custom_rules:
  pso_prefix_rule:
    name: "PSO Prefix Rule"
    regex: '\b(class|struct|enum|protocol) (?!(PSO))'
    message: "Top-level classes, structs, enums, and protocols should start with a 'PSO' prefix."
    severity: warning

This works, but also for non-top identifiers for example:

public struct PSOStruct {
    enum MyEnum { // Gets triggered

    }
}

Is there any way to achieve enforcing the prefix only on top-level identifiers?

0

There are 0 answers