Using dispatch_once to create a singleton in Swift: how to do it correctly?
Hello everyone! I just started learning Swift after Objective-C, and I ran into a problem implementing the singleton pattern. In Objective-C, I used to use dispatch_once to ensure that initialization happens only once, even in a multithreaded environment. Something like this:
```
+ (instancetype)sharedInstance {
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
});
return sharedInstance;
}
```
Now I'm trying to do the same in Swift. I read that Swift has let and static properties, which are thread-safe by default. But I don't quite understand how it works. I tried writing it like this:
```
class MyClass {
static var shared: MyClass {
d
No answers yet.
Log in to leave an answer
Blogs
Swift 2025: Where to Start Learning the Language for iOS/macOS
How to Become a Kotlin Developer: Tips and Resume in Practice
Top Mistakes of Beginner C++ Developers: Advanced Level
Converting a string to a byte array in C#: a complete guide