Search code examples
objective-cswiftsingletonclass-method

How do you call a singleton class method from Objective C in a Swift class?


I have the following objective C code which I need to get into a Swift class :

In Logger.m -

+ (Logger *) log
{
static Logger *sharedLog = nil;
static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{
    sharedLogger = [[self alloc] init];
});

return sharedLogger;
}

- (void) printString:(NSString *) s
{
    NSLog(s)
}

Which is in Logger.h as -

+ (Logger *) log;
- (void) printString:(NSString *) s;

Now, I have this code bridged in to Swift Project - LoggerUserApp where I'm trying to use the above print method from the singleton log shared class method.

I've tried -

Logger.log().printString("String")  // Compiler Error. Use Object Construction Logger()
Logger().log().printString("String")  // Compiler Error. 
Logger().log.printString("String") // Compiler Error. 
Logger.printString("String") // This does not call log

Can someone tell me what might be going wrong?


Solution

  • In the Swift update, if the class method's name is similar to the class name, then it just takes that as a custom initializer. Now since there was no parameter in the method, it wouldn't come up as the default initializer would come up instead.

    Hence, to solve this problem, I had to change the name of the class method log to something different like newLog... and it worked fine.

    Logger.newLog().printString("")