title: Thread safe singleton in swift
body: <p>I have and Application which has a <strong>singleton</strong> that stores information across the whole app. However, this is creating some data race issues when using the singleton from different threads. </p>
  
  <p>Here there is a very dummy and simplistic version of the problem:</p>
  
  <p><strong>Singleton</strong></p>
  
  <pre><code>class Singleton {
      static var shared = Singleton()
  
      var foo: String = "foo"
  }
  </code></pre>
  
  <p><strong>Use of the singleton</strong> (from the AppDelegate for simplicity)</p>
  
  <pre><code>class AppDelegate: UIResponder, UIApplicationDelegate {
  
      var window: UIWindow?
  
  
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -&gt; Bool {
          // Override point for customization after application launch.
  
          DispatchQueue.global().async {
              var foo = Singleton.shared.foo // Causes data race
          }
  
          DispatchQueue.global().async {
              Singleton.shared.foo = "bar"   // Causes data race
          }
  
          return true
      }
  }
  </code></pre>
  
  <p>Is there any way to ensure that a singleton is thread safe, so it can be used from anywhere in the app without having to worry about which thread you are in?</p>
  
  <p>This question is <strong>not</strong> a duplicate of <a href="https://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift">Using a dispatch_once singleton model in Swift</a> since (if I understood it correctly) in there they are addressing the problem of accessing to the singleton object itself, but not ensuring that the reading and writing of its properties is done thread safely. </p>