Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate method must be declared public

Tags:

ios

swift

Let's say I have a class

public class MyClass: NSObject, ABCDelegate {
    func delegateMethod(a: a, b: b) {
        ...
    }
}

This delegate method is being called by a singleton in MyClass that handles some networking operations.

The thing is the compiler complains about Method 'delegateMethod(...)' must be declared public because it matches a requirement in public protocol 'ABCDelegate'.

My question is:

  1. Why exactly is the compiler complaining for the method being declared as private func or simply func
  2. How can I declare the ABCDelegate methods to be private to this class?
like image 749
Thanos Avatar asked Feb 04 '15 19:02

Thanos


1 Answers

If ABCDelegate is declared public and MyClass which adopts it is declared public, then the MyClass implementation of any members required by ABCDelegate must be declared public. It's as simple as that.

And if you think about it, it couldn't work any other way. Knowledge of MyClass is public. Knowledge of ABCDelegate is public. Knowledge of the fact that MyClass adopts ABCDelegate is public. Therefore knowledge of the fact MyClass implements the required members of ADCDelegate must be public - it follows as the night the day.

If you really wanted to, you could work around this by inserting a nonpublic object type into the chain of command. This compiles fine:

public protocol Proto {
    func f()
}
public class A {
    private var helper : B!
    func g() {
        helper.f()
    }
}
private class B : Proto {
    func f() {}
}

But it seems awfully silly. My recommendation is just do what the compiler tells you and move on.

like image 97
matt Avatar answered Oct 04 '22 11:10

matt