Avatar ·

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