12

How do I create a method in an extension and have it only accessible inside the class (or its subclasses), like a private method, but declared in another file inside an extension?

private won't work, because it has to be inside the same declaration.

fileprivate won't work, because it has to be on the same file.

public or the default won't work, because it will be visible from other classes.

Am I missing something?

I'm looking for something like extensionprivate or classprivate.

mfaani
  • 33,269
  • 19
  • 164
  • 293
Rodrigo Ruiz
  • 4,248
  • 6
  • 43
  • 75
  • 5
    What is your motivation? Why not just create a private method inside the class itself? The whole point of extension is to bring extra functionality that classes do not have and use it everywhere. – kmarin Aug 24 '17 at 15:27
  • Look at this answer https://stackoverflow.com/a/39748056/5327882 – ronatory Aug 24 '17 at 15:28
  • 3
    You're not missing anything; this isn't currently possible. – jscs Aug 24 '17 at 15:36
  • @KeranMarinov the motivation is to reuse that method across different subclasses. – Rodrigo Ruiz Aug 24 '17 at 15:37
  • Java has protected keyword for methods only accessible from subclasses, don't think Swift has it yet. I would also suggest, rather than subclassing from single class, you can have protocol with default implementation. – kmarin Aug 24 '17 at 16:00
  • There is also internal keyword which allows module level access. – kmarin Aug 24 '17 at 16:10
  • I'm ok doing it in a protocol, but this would still make the method public to the rest of my project. – Rodrigo Ruiz Aug 24 '17 at 20:03

2 Answers2

2

Currently Swift 3 has some problems due to Private accessibility within the Extensions. In swift4 it will be possible. You can try with Xcode 9 beta.

swift2geek
  • 1,697
  • 1
  • 20
  • 27
0

What you're asking is not possible to do at the moment, and I agree that it would be very helpful in some cases.

Let's say we have this protocol:

protocol HidableViewed {
    var hidableView: UIView
}

This protocol is used to signify that some view controller has a view that can be hidden (which makes sense in its business case).

So what do we want with hidable views? We want to hide them of course, but hiding operation is same in each instance of this protocol. So to avoid rewriting the hiding method in each view controller, we want to implement it once in our protocol.

extension HidableViewed {
    func hideView() {
        self.hidableView.isHidden = true
    }
}

Very nice, how convenient!

There's one problem though: if a view controller implements this protocol, any other class will be able to hide its view. And we certainly don't want that in some cases, which brings us to the original question.

Sarp Başaraner
  • 505
  • 7
  • 17