12

I added Swiftlint to a project and I'm having trouble understanding what the warning is for extension_access_modifier. I see it mainly on a class that is declared as public, but there are extensions littered throughout the codebase that adds functionality.

public class Foo {

}

// In SomeOtherClass.swift
extension Foo { // Extension Access Modifier Violation: Prefer to use extension access modifiers
    public func baz()
}

Whenever there is extension Foo in another class, I get that warning on the extension. Would someone explain what it is?

mfaani
  • 33,269
  • 19
  • 164
  • 293
Crystal
  • 28,460
  • 62
  • 219
  • 393
  • it probably prefers the `extension` be `public`, rather than the `func` – Alexander Feb 01 '18 at 00:23
  • @Alexander When I add public to the extension (e.g. `public extension foo`), the warning then appears on the `public func baz()` method – Crystal Feb 01 '18 at 00:24
  • if the `extension` is explicitly `public`, the `func` doesn't need too be – Alexander Feb 01 '18 at 00:24
  • @Alexander can you put your comment in the answer. that worked. public extension without the public on the baz() function. – Crystal Feb 01 '18 at 00:26

1 Answers1

21

It's clearer to express that your extension is public, rather than all its members:

Prefer:

public extension Foo {
    func bar() { ... }
    func baz() { ... }
    func qux() { ... }
}

over

extension Foo {
    public func bar() { ... }
    public func baz() { ... }
    public func qux() { ... }
}
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • 1
    lol. My project has the exact opposite. I guess it's there to avoid spamming the user of your library with your extensions i.e. I'm getting: 'No Extension Access Modifier Violation: Prefer **not** to use extension access modifiers (no_extension_access_modifier)' – mfaani Jan 20 '21 at 20:09
  • @Honey Both variants I show end up `spamming the user of your library with your extensions`. `bar`, `baz` and `qux` are still public in both variants. – Alexander Jan 20 '21 at 22:32
  • True. I was just pointing out the my swiftlint will pop a warning if you do `public extension Foo`. I landed at this page when I was searching for the error _I_ got. It's similar to the error in the question, but yet totally the opposite – mfaani Jan 20 '21 at 22:58
  • 1
    Except that it complains even if you have only one function. Not sure that is helpful: ```extension AppDelegate { public func initXxxxx() {} ``` Because any latter functions you add, you might not want those to be public. Or they might end up public by mistake. – Jonny Apr 11 '23 at 07:09