How can I initiate an instancetype from Objective-C with Swift

2.5k Views Asked by At

I have an api that I have to translate it from Objective-C to Swift. I'm stuck with some type of constructor or initialization I don't really know.

This is how the .h file is:

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

This is how .m file is:

+ (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;
}

This is the call that they have to the main file I'm translating:

mobileApi = [MobileAPI newDemoInstance];

So I want to convert only the last line to Swift 2.

4

There are 4 best solutions below

0
Magoo On BEST ANSWER
var mobileApi = MobileAPI.newDemoInstance()

or

let mobileApi = MobileAPI.newDemoInstance()

if you don't intend to modify it.

0
Nirav D On

It simply MobileAPI.newDemoInstance().

let mobileApi = MobileAPI.newDemoInstance()

Note: Don't forgot to import MobileAPI.h in Bridging-Header.h file.

1
Nikhil Manapure On

I hope this helps

 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
Mehmet Baykar On

The best option to make instance type in objective-c that works in objective-c and Swift you should use "default" keyword. This keyword has been used in the standard libraries of Apple. For example NSNotificationCenter.default or NSFileManager.default. To declare it in the .h file you should write

+(instancetype) default;

and in your .m file

static YOUR_CLASS_NAME *instance = nil;

+(instancetype) default {
if instance == nil { instance = [[super allocWithZone:NULL] init];}
return instance;
}