Joe Blow Joe Blow - 6 months ago 8
Swift Question

Any reason not use use a singleton "variable" in Swift?

For Sept 2015, here's exactly how you make a singleton in Swift:

public class Model
{
static let shared = Model()
// ( for ocd friends ... private init() {} )

func test()->Double
{
return 3.33
}
}


then elsewhere...

// file ViewController.swift, say
import UIKit
class ViewController:UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
print("view controller loaded!")
print("singleton test! \( Model.shared.test() )")
}
}


No problem.

However, I like to do this:

public let model = Model.shared
public class Model
{
static let shared = Model()

func test()->Double
{
return 3.33
}
}


then, you can simply do the following project-wide:

class ViewController:UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
print("view controller loaded!")
print("singleton test! \( model.test() )")
}
}


Conventional idiom:

Model.shared.test() ... you see this everywhere in the code base



"my" idiom:

model.test() ... you see this everywhere in the code base



So, this results in everything looking pretty:

enter image description here

(In your project, those "singleton variables" would be things like
scores.
,
networking.
,
heuristics.
, or whatever the case may be in your project.)

This then, let us boldly admit it, is a

"macro-like" idiom,

the purpose of which is clarity ... simplifying appearances of
ImportantSystem.SharedImportantSystem
down to
importantSystem.
throughout the project.

Can anyone see any problems with this idiom?



Problems may be technical, stylistic, or any other category, so long as they are really deep. Get out the LSD.

Rob Rob
Answer

Functionally, these are very similar, but I'd advise using the Model.sharedModel syntax because that makes it absolutely clear, wherever you use it, that you're dealing with a singleton, whereas if you just have that model global floating out there, it's not clear what you're dealing with.

Also, with globals (esp with simple name like "model"), you risk of having some future class that has similarly named variables and accidentally reference the wrong one.

For a discussion about the general considerations regarding globals v singletons v other patterns, see Global Variables Are Bad which, despite the fairly leading title, presents a sober discussion, has some interesting links and presents alternatives.