0

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

    }
1
  • 1
    +(id)sharedSearchItem is a class method, not a static function. Commented Jun 3, 2017 at 1:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response! thats great to know, but what If I want to initialize later on the variables that are in the super class, the SearchItem() will instantiate everything but If I want to initialize with a specific setting as in the configure function shows?
Why not just make those variables mutable, and run your configure function whenever you need to set those properties. You'd just need to call SearchItem.sharedSearchItem.configureWithSettings(...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.