Kex Kex - 2 months ago 91
iOS Question

Swift 3.0 Static instances, change in syntax from migration tool

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?

Answer

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.