Reputation: 4355
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
.
Upvotes: 13
Views: 3546
Reputation: 516
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.
Upvotes: 0
Reputation: 1812
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.
Upvotes: 2