Why delegate methods needs to be public in Swift?

限于喜欢 提交于 2019-12-10 16:35:34

问题


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 {
}

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) {

    //}
}

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?


回答1:


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
    }
}

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
}


来源:https://stackoverflow.com/questions/34154525/why-delegate-methods-needs-to-be-public-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!