0

In a class I would previously create a shared instance like so:

class MenuConfigurator
{
  // MARK: Object lifecycle

  class var sharedInstance: MenuConfigurator
  {
    struct Static {
      static var instance: MenuConfigurator?
      static var token: dispatch_once_t = 0
    }

    dispatch_once(&Static.token) {
      Static.instance = MenuConfigurator()
    }

    return Static.instance!
  }

}

It seems the Swift 3.0 migration tool has changed the block of code to:

class MenuConfigurator
{
  private static var __once: () = {
      Static.instance = MenuConfigurator()
    }()
  // MARK: Object lifecycle

  class var sharedInstance: MenuConfigurator
  {
    struct Static {
      static var instance: MenuConfigurator?
      static var token: Int = 0
    }

    _ = MenuConfigurator.__once

    return Static.instance!
  }

}

I am getting the error Use of unresolved identifier Static. What is happening here? Why has the new var private static var __once been created?

Kex
  • 8,023
  • 9
  • 56
  • 129
  • Hi, Converting project to swift 3 is really a nightmare.. Have you tried to put your previous code and see what errors it gives. From that you might come to know why conversion tool changed it this way. Also `static` you can use in swift 3 also. I am using it. but only with small `s` – Bhagyashree Dayama Sep 27 '16 at 10:38

1 Answers1

2

dispatch_once_t has been dropped in Swift 3.

The recommended way (at least since Swift 2) to create a singleton is simply

class MenuConfigurator
{
  static let sharedInstance = MenuConfigurator()
}

let configurator = MenuConfigurator.sharedInstance

Forget the suggestion of the migrator.

vadian
  • 274,689
  • 30
  • 353
  • 361