ios - 委托(delegate)方法必须公开

标签 ios swift

假设我有一个类

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

此委托(delegate)方法由 MyClass 中处理某些网络操作的单例调用。

问题是编译器提示 Method 'delegateMethod(...)' must be declared public because it matches a requirement in public protocol 'ABCDelegate'

我的问题是:

  1. 为什么编译器会提示方法被声明为 private func 或简单地 func
  2. 如何将 ABCDelegate 方法声明为此类的私有(private)方法?

最佳答案

如果ABCDelegate被声明为public,而采用它的MyClass也被声明为public,那么ABCDelegate需要的任何成员的MyClass实现都必须被声明为public。就这么简单。

如果您考虑一下,它无法以任何其他方式工作。 MyClass 的知识是公开的。 ABCDelegate 的知识是公开的。 MyClass 采用 ABCDelegate 这一事实是公开的。因此,MyClass 实现所需的 ADCDelegate 成员这一事实的知识必须是公开的——它会在白天的夜晚发生。

如果您真的想这样做,可以通过在命令链中插入一个非公共(public)对象类型来解决这个问题。这编译得很好:

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

但这看起来非常愚蠢。我的建议是按照编译器告诉你的去做,然后继续。

关于ios - 委托(delegate)方法必须公开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28329563/

相关文章:

ios - 在 swift 中声明这些变量时有什么区别!或者 ()

ios - MPMoviePlayerController 只想要视频,没有音频

ios - 如何使用 ios-charts 在饼图 View 中获取所选切片的索引?

swift - Firebase Firestore + Cloud Function 服务器端验证应用内购买收据(Swift + NodeJS)

ios - 在 swift 中的 Realm 中插入多行

swift - 哪个更好 removeAll of Array 并再次初始化 Array?

ios - Swift - 闭合模式

objective-c - iPhone 中的图像处理

ios - Swift-检测点击 NSMutableAttributedString

ios - 点击由 UIScrollView 覆盖的 UITableViewCell 中的 UIButton 不会触发按钮的目标