2016-11-30 43 views
2

我有一个API,我必须将它从Objective C转换为Swift。 我坚持使用某种类型的构造函数或初始化我不太了解。如何用Swift从Objective C启动实例类型

这是.h文件如何:

+ (instancetype) newProductionInstance; 
+ (instancetype) newDemoInstance; 

这是文件的.m怎么是:

+ (instancetype) newProductionInstance 
{ 
    return [[self alloc] initWithBaseURLString:productionURL]; 
} 

+ (instancetype) newDemoInstance 
{ 
    return [[self alloc] initWithBaseURLString:demoURL]; 
} 

- (instancetype)initWithBaseURLString:(NSString *)urlString 
{ 
    if (self = [self init]) 
    { 
     _apiURL = [NSURL URLWithString:urlString]; 
    } 
    return self; 
} 

这是呼叫自己要我翻译的主要文件:

mobileApi = [MobileAPI newDemoInstance]; 

所以我只想最后一行转换为斯威夫特2

在此先感谢。

回答

2
var mobileApi = MobileAPI.newDemoInstance() 

let mobileApi = MobileAPI.newDemoInstance() 

,如果你不打算修改它。

+0

感谢那些工作。 (我会在4分钟内接受) –

1

它只是MobileAPI.newDemoInstance()

let mobileApi = MobileAPI.newDemoInstance() 

注:不要忘了在​​文件导入MobileAPI.h

1

我希望这有助于

class YourClass: NSObject { 
    //Class level constants 
    static let productionURL = "YourProductionURL" 
    static let demoURL = "YourDemoURL" 

    //Class level variable 
    var apiURL : String! 

    //Static factory methods 
    static func newProductionInstance() -> YourClass { 
     return YourClass(with : YourClass.productionURL) 
    } 

    static func newDemoInstance() -> YourClass { 
     return YourClass(with : YourClass.demoURL) 
    } 

    // Init method 
    convenience init(with baseURLString : String) { 
     self.init() 
     self.apiURL = baseURLString 

     //Calling 
     let yourObject : YourClass = YourClass.newDemoInstance() 
    } 
} 
+0

*,应该以小写字母 – user28434

+1

@ user28434开头,谢谢指出错误。 –