0

In swift, how do I make an extension visible to only a few classes and not to all?

I have added an extension to UIImage in a file called UIImage+filters.swift. I will be using this extension only in 2 classes in my project PhotoImage and PhotosViewController. I want the extension to be visible only to these 2 classes. How can I achieve this?

iOSer
  • 235
  • 2
  • 14
  • 1
    The point of a class extension is to extend the class for all instances of that class. It sounds like your functionality is highly specific and therefore more suited to a helper class. – Mike Taverne Sep 02 '16 at 04:05

2 Answers2

1

That's not possible, access modifiers of classes/extensions behave consistent through all units, separating privileges between outside modules and module where they are. That means that you can declare your class/extension be accesible inside your app/module and not accesible to outsiders or visible to everybody.

Swift3 comes with a new access modifier, but nothing to restrict access partially inside the module/app.

Jans
  • 11,064
  • 3
  • 37
  • 45
0

There is no concept of "friend" classes in Swift. But you can hack your way through it by using private in your extension. For this to work, the extension class and your PhotoImage and PhotosViewController must be in one file. By using private in your UIImage extension, the added function is only visible in this file and will not be visible in other files.

PhotosViewController.swift

private extension UIImage
{
  func applyFilter()
  {
  }
}


class PhotosViewController : UIViewController
{
  // applyFilter function in visible in this class
} 

AnotherViewController.swift

class PhotosViewController : UIViewController
{
  // applyFilter function in NOT visible in this class
}
Christian Abella
  • 5,747
  • 2
  • 30
  • 42