Search code examples
swiftsingleton-methods

How can I create a instance like objective-c do?


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?


Solution

  • 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:

    class BaseClass {
    
        class func task() -> BaseClass {
            return BaseClass()
        }
    
        // ...
    
    }
    
    class ChildClass : BaseClass {
    
        override class func task() -> ChildClass {
            return ChildClass()
        }
    
        // ...
    
    }
    

    then you would be able to get instances like this:

    let bTask: BaseClass = BaseClass.task()
    let cTask: ChildClass = ChildClass.task()
    

    case #2

    you can also do something like this, if such thing looks more reasonable for you:

    class BaseClass {
        
        class var task: AnyObject {
            get {
                return self.init()
            }
        }
        
        required init() {
            
        }
        
        // ...
    
    }
    
    class ChildClass : BaseClass {
        
        // ...
    
    }
    

    then you can instantiate your classes like:

    let bTask: BaseClass = BaseClass.task as! BaseClass
    let cTask: ChildClass = ChildClass.task as! ChildClass
    

    case #3

    here is an other option for you too, if you are not happy with any of the ideas above:

    class BaseClass {
        
        class func task() -> Self {
            return self.init()
        }
        
        required init() {
            
        }
        
        // ...
    
    }
    
    class ChildClass : BaseClass {
        
        // ...
    
    }
    

    the instantiation is similar to the first case:

    let bTask: BaseClass = BaseClass.task()
    let cTask: ChildClass = ChildClass.task()
    

    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.