我的目标是编写一个类并在其中包含一个函数,该函数包含在后台线程中运行的代码(例如在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的要求?
顺便说一句,我已经看到有关这方面的问答,没有合理的方法伪造受保护的访问级别。我不需要伪造它,我只需要另一种方法来实现将代码隐藏在来自除基类之外的所有世界的派生类中的目标,或类似的东西。
我很想使用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!
}
}