您好,我目前正在將一個在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
}
'+(id)sharedSearchItem'是一個類方法,而不是一個靜態函數。 – Willeke