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
.
You might be confused by the term "extension method". It is not a method in the class or even a derived class; It is an operation on a type. It has no access to the private, protected or internal members of the class hierarchy and therefore the class is still sealed. So, you can't and don't need to.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
An extension method must be a static method. An extension method must be inside a static class -- the class can have any name. The parameter in an extension method should always have the "this" keyword preceding the type on which the method needs to be called.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With