到目前为止,我只参与过Objective-C项目,现在开始了我的第一个Swift项目。
我知道Swift不支持抽象类,但我想知道在Swift中建模/解决这个问题的最佳方法是什么:
// Abstract implementation
public abstract class MyClass {
private SomeBaseClass someProperty;
MyClass() {
initProperties();
}
abstract void initProperties(); // Init someProperty with some child class of SomeBaseClass.
}
// Objectiv-C
@implementation MyClass
- (id)init {
self = [super init];
if (self) {
[self initProperties];
}
return self;
}
- (void)initProperties {
// Override in inherited classes
}
// Swift
class MyClass {
// Should not be optional since MyClass should be required to have someProperty != nil
let someProperty: SomeBaseClass;
override init() {
super.init();
initProperties();
}
func initProperties() {
// Cannot be empty since someProperty is non-optional and needs to be initialized
// Cannot be empty since Swift does not support abstract methods
}
}
当然,将
someProperty
定义为可选的SomeBaseClass?
也是可能的,但在这种情况下,每次使用该属性时都必须进行测试和解包。有更好的方法来解决这个问题吗?
编辑:
我知道Swift使用协议来创建类似于抽象类的抽象。然而,我不明白这个概念如何解决具体的问题/问题。
在其他编程语言中,抽象类
MyClass
可以在许多不同的地方使用属性someProperty
,同时留下将该属性初始化为具体子类的负担。尽管我阅读了@MohamendS链接的文章以及可能重复回答的答案,但我不明白如何使用协议实现相同的功能。
-
MyClass
只有一个抽象函数,而所有其他函数都已实现。因此MyClass本身不能成为协议,因为协议不能实现函数(它们能吗?)
- MyClass
只能实现另一个定义了必须有一个 initProperties
方法的协议。但在这种情况下, MyClass
需要提供此方法的实现,这使我们回到了同样的问题。我想我看不到树木,但协议怎么能帮助这里呢?
someProperty
,因为它从未被使用。”但对于你的具体问题,几乎肯定不是正确的答案。我们只是不知道你的具体问题是什么,所以很难讨论哪种协议是适当的。协议是一种不同于抽象类的思考问题的方式。 - Rob Napier