Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method accessible only inside class

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.

like image 328
Rodrigo Ruiz Avatar asked Aug 24 '17 15:08

Rodrigo Ruiz


People also ask

Can we use extension method in sealed class?

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.

What is the extension method for a class?

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.

Can extension methods only extend static classes?

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.


1 Answers

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.

like image 64
swift2geek Avatar answered Sep 23 '22 13:09

swift2geek