paul590
paul590

Reputation: 1425

Initializing object from static variable Objective C to Swift

Hello I am currently translating a project that was written in Objective C into swift and I am running into a puzzle. In objective C the Object (SearchItem) is a sub class of object Item and has a static variable of the same class (SearchItem). The static variable is initialized in a static function. The problem is on objective C there is a non-static function that initializes the super class variables, I tried to replicate this but I am not 100% how to approach this, I would like to keep the same format if possible, any help would be great!

Obj C:

.h file includes:

 @interface SearchItem : Item

.m file includes:

static SearchItem *sharedSearchItem = nil;

+(id)sharedSearchItem {
    @synchronized(self) {
        if(sharedSearchItem == nil){
            sharedSearchItem = [SearchItem new];
            //other methods
        }
    }
    return sharedSearchItem;
}
-(void)configureWithSettingsConfig:(SettingsConfig *)settings{
    NSLog(@"%@", [super initWithSettings:settings]);
    //Other methods 
}

Swift:

static var sharedSearchItem: SearchItem? = nil

static func sharedSearchItemInit(){
        if(sharedSearchItem == nil){
            sharedSearchItem = SearchItem()
            //Other methods
        }
    }

    func configureWithSettingsConfig(settings: SettingsConfig){
        print(SearchItem.init(settings: settings)) // creates separate object need it to be on same instantiation
        /*
        The following calls won’t work
        self = ServiceFacade.init(settings: settings)
        self.init(settings: settings)
        super.init(settings: settings)*/
        //Other methods

    }

Upvotes: 0

Views: 342

Answers (1)

creeperspeak
creeperspeak

Reputation: 5523

In Swift the way we create Singletons is simply like so:

static let sharedSearchItem = SearchItem()

That's it. No need for a special "sharedInit" function.

Upvotes: 2

Related Questions