2017-06-02 63 views
0

您好,我目前正在將一個在Objective C中編寫的項目翻譯成swift,而我正在運行一個謎題。在Objective C中,對象(SearchItem)是對象Item的子類,並且具有相同類(SearchItem)的靜態變量。靜態變量在靜態函數中初始化。問題是在目標C有一個非靜態函數初始化超類變量,我試圖複製這個,但我不是100%如何處理這個,我想保持相同的格式,如果可能的話,任何幫助將太好了!從靜態變量Objective C初始化對象到Swift

的OBJ C:

.h文件中包括:

@interface SearchItem : Item 

.m文件包括:

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 
} 

斯威夫特:

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

'+(id)sharedSearchItem'是一個類方法,而不是一個靜態函數。 – Willeke

回答

2

在斯威夫特我們創建的方式單身人士就像這樣:

static let sharedSearchItem = SearchItem() 

就是這樣。不需要特殊的「sharedInit」功能。

+0

謝謝你的迴應!這很好知道,但如果我想稍後初始化超類中的變量,SearchItem()將實例化所有內容,但是如果我想使用特定設置進行初始化,如configure函數中所示? – paul590

+1

爲什麼不讓這些變量變爲可變的,並在需要設置這些屬性時運行'configure'函數。你只需要調用'SearchItem.sharedSearchItem.configureWithSettings(...' – creeperspeak

+0

謝謝你的幫助,這解決了我的問題! – paul590