为什么委托方法需要在Swift中公开? [英] Why delegate methods needs to be public in Swift?

查看:152
本文介绍了为什么委托方法需要在Swift中公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在迅速开发一个框架.我正在创建一个处理框架中BLE内容的类.此类应为公共类,因为我需要从使用我的框架的外部应用程序访问此类.我的课程结构如下:

I am working on a framework in swift. I am creating a class which deals with BLE stuff in the framework. This class should be public as I need to access this class from external application which uses my framework. My class structure is a below:

public class MyClass: NSObject, CBCentralManagerDelegate {
}

此处MyClass是公共的,这确认了公共协议CBCentralManagerDelegate.编译器迫使我将其委托方法声明为public.所以这是我的实现方式:

Here MyClass is public, which confirms a public protocol CBCentralManagerDelegate. Compiler force me to declare it's delegate methods as public. So here is what my implementation looks like:

public class MyClass: NSObject, CBCentralManagerDelegate {
    public func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {

    }
    // I don't want delegate methods to be public, delegate  methods should be like: 
    //func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {

    //}
}

我已经在此处浏览了苹果文档和一个SO问题此处.我知道,由于我的类和协议都是公共的,因此方法也应该是公共的.

I have explore apple document here and a SO question here. I came to know that as my class and protocol both are public the methods should be public.

问题是,外部应用程序可以轻松地创建我的类的实例并调用此方法,这是我的框架所期望的.

The problem with this is, an external application can easily create instance of my class and call this method, which my framework doesn't expect.

我想使委托方法保持私有状态,因此没有人可以手动调用它们.

I would like to keep the delegate methods private so no one can call them manually.

我有什么可能的解决方案?

What are the possible solution I have?

推荐答案

尝试在公共类中隐藏公共协议的方法没有多大意义,因为它首先破坏了使用协议的目的.

Trying to hide the methods of a public protocol in a public class doesn't make much sense, because it defeats the purpose of using protocols in the first place.

如果您确实需要隐藏它们,则可以添加一个私有实例变量来充当委托,而不是像这样的类本身:

If you really need to hide them, you can add a private instance variable that will act as a delegate instead of the class itself like this:

public class MyClass: SomeClass
 {
    private let someVariable
    private var subdelegate :DelegateType?

    public override func viewDidLoad()
    {
        super.viewDidLoad()
        subdelegate = DelegateType(parent: self)
        someOtherObject.delegate = subdelegate
    }
}

然后在DelegateType中实现委托方法.

Then implement the delegate methods in the DelegateType.

private class DelegateType : NSObject, HiddenProtocol 
{
    private weak var parent: MyClass?

    init(parent: MyClass)
     {
        super.init()
        self.parent = parent
    }

    // Implement delegate methods here by accessing the members 
    // of the parent through the 'parent' variable
}

这篇关于为什么委托方法需要在Swift中公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆