2016-11-30 1 views
2

Objective C에서 Swift로 변환해야하는 API가 있습니다. 일부 유형의 생성자 또는 초기 설정이 잘못되어 있습니다.Swift를 사용하여 Objective C에서 instancetype을 초기화하는 방법

이것은 .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() 

참고 :Bridging-Header.h 파일에 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로 시작해야합니다. –

관련 문제