我可以得到类似的最终结果到C#的“受保护”访问但在Swift中?

问题描述 投票:2回答:1

我的目标是编写一个类并在其中包含一个函数,该函数包含在后台线程中运行的代码(例如在run()函数中)。以下是我的课程(及相关课程)的一些要求:

  • 确保当我编写run()函数时,代码保证在后台线程中运行,而程序员不需要知道任何有关线程的信息,也不必记住调用与线程相关的run()函数中的任何其他代码。 。
  • 具有在其他地方设置的完成函数函数,该函数在后台线程完成其处理时调用,而程序员不必在此run()函数中编写代码来进行调用。
  • 几乎让某人从某个基类派生一个类,然后在run()函数中编写它们的后台代码,而不编写与管理后台线程,完成函数等相关的任何其他内容。

这是我可能用C#编写的代码,在两个不同的文件中:

class MyBase
{
    public Action completionFunction = NULL;
    public void begin()
    {
        RunInOtherThread( run ); // This function call is just pseudo-code for running that run() function in a background thread.
        if( completionFunction != Null )
            completionFunction();
    }
    virtual protected void run() = 0 // so this class cannot be instantiated
    {
    }
};

在另一个文件中:

class MySpecificClass : MyBase
{
    override void run()
    {
        // Do important stuff here!
    }
};

我不知道如何满足我在Swift中的要求。由于对我来说没有意义的原因,他们忽略了“受保护”的保护级别(比如认为我不能通过公共函数暴露基类保护函数来解雇程序员搞砸了代码)。

我不熟悉Swift的一些功能来获得这些结果。我不需要让类像C#代码一样工作,即使它对我和我的C#程序员来说是一个非常好的解决方案。

我怎样才能满足Swift的要求?

顺便说一句,我已经看到有关这方面的问答,没有合理的方法伪造受保护的访问级别。我不需要伪造它,我只需要另一种方法来实现将代码隐藏在来自除基类之外的所有世界的派生类中的目标,或类似的东西。

swift multithreading protected
1个回答
0
投票

我很想使用protocols,而不是分类。例如:

public protocol MyBase {
    // *** This requires any object that conforms to the protocol
    // *** to provide these, without specifying what they do
    var completionFunction: (() -> ())? {get set}
    func run() 
}
public extension MyBase {
    // *** This extension provides all objects that conform to the 
    // *** protocol with this function
    func begin() {
        RunInOtherThread( self.run ) // This function call is just pseudo-code for running that run() function in a background thread.
        if let c = self.completionFunction {
            c()
        }
    }
}

public class MySpecificClass: MyBase {
    // *** Now, rather than subclassing, we simply conform to the protocol 
    public var completionFunction: (() -> ())? = nil
    public func run() { 
        // *** No need to `override` - but *must* be supplied
        // Do important stuff here!
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.