Using Objective-C Singleton in Swift file within Objective-C project

Hello everyone,

I've got my project written in Objective-C. I am learning about bridging.

I bridged successfully Swift into my Objective-C project. I did some VC pushing between Objective-C VC and Swift VC. Everything works as it supposed to.

However, I created the reference to my Objective-C NetworkManager (I used Singleton pattern) in my Swift file like that:
Code Block
let networkManager = NetworkManager.sharedManager()

For some reason I cannot use methods from it.
Code Block
networkManager.getUserInfo() // .getUserInfo() will not appear!

Just to show you how I've created my NetworkManager as a Singleton. I found that solution online and it was quite old, if you have any better solution, I would be more than happy to get some insight:
Code Block
+ (id)sharedManager {
static NetworkManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
-(id)init {
if (self = [super init]) {
someProperty = @"Default Property Value";
self.cache = [[NSCache alloc] init];
}
return self;
}


Not sure what is the issue here. Thank you all for the help.
Answered by OOPer in 673798022
The return type (id) is not good for bridging to Swift.

Can't you give it an explicit return type?
Code Block
+ (NetworkManager *)sharedManager {


Accepted Answer
The return type (id) is not good for bridging to Swift.

Can't you give it an explicit return type?
Code Block
+ (NetworkManager *)sharedManager {


Fantastic. Thank You.

Would you mind telling me why is not a good idea to use id with Swift?

Would you mind telling me why is not a good idea to use id with
Swift?

Swift is a much more strongly-typed language than Objective-C. id is equivalent to Swift’s Any, which means it carries no type info, and that makes it hard to use from Swift.

Swift has some features that can help with this but they are limited to AnyObject, rather than Any, and modern versions of Swift translate id to Any (see SE-0116).

Keep in mind that id is typically a bad idea even in Objective-C. While Objective-C won’t stop you from using it, doing so seriously undermines the compiler’s ability to warn your about type errors. So OOPer’s suggestion will help in both languages!

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Using Objective-C Singleton in Swift file within Objective-C project
 
 
Q