Usually, I create a class's instance like this:
The Parent class:
@interface baseClass
+ (instancetype)task;
@end
@implement baseClass
+ (instancetype)task {
return [[[self class] alloc] init];
}
@end
and then in children class:
@interface childClass : baseClass
@end
@implement childClass
@end
Finally, I can create a instance using:
childClass *pChild = [childClass task];
How could I implement this feature by using the Swift programming language?
In another word, how could I implement the [[[self class] alloc] init] in swift way?
I feel a bit insecure about you tagged your question as a singleton but basically the code you presented has nothing to do with singletons at all, so I tried to mimic your original classes and show a few options here.
these are written in Swift 2.2.
case #1
that works flawlessly initially:
then you would be able to get instances like this:
case #2
you can also do something like this, if such thing looks more reasonable for you:
then you can instantiate your classes like:
case #3
here is an other option for you too, if you are not happy with any of the ideas above:
the instantiation is similar to the first case:
NOTE: you may need to refine the chosen concept for your final code if you want to deal with real singletons, these examples are not perfectly worked out as I mentioned at the beginning but they show you a few options you can have and you can use as template.