0

I'm currently working on an app which requires that information be shared between multiple views. For simplicity's sake, I prefer to use a singleton for said purpose.

My questions are...

  1. Where should a singleton class be defined and initialized so that it is available to all view controllers and all other class files?
  2. How should other classes reference said singleton? Are any import statements or special initializations within a specific class necessary?

I'd just like to mention that I'm intrigued by the one line singleton found @ http://krakendev.io/blog/the-right-way-to-write-a-singleton

Such a method would be preferable.

BTW: I'm developing using Swift in Xcode 6.2

Thanks.

rmaddy
  • 298,130
  • 40
  • 468
  • 517
HumbleOne
  • 150
  • 9
  • FYI - the version of Xcode is irrelevant. The version of Swift is important. – rmaddy Nov 05 '16 at 16:55
  • Don't use a singleton for this. It's a poor design decision. – rmaddy Nov 05 '16 at 16:56
  • Yeah; singletons are an easy solution to problems like these but usually will end up making things more complex down the line. What sort of data do you need to share? Would you mind giving an example? – Olivier Wilkinson Nov 05 '16 at 17:26

1 Answers1

0

If you define a singleton, it's available everywhere in your target. So put it wherever you want, generally its own .swift file. And to use it, you'd simply do the following, with no special import statements needed:

let kraken = TheOneAndOnlyKraken.sharedInstance

BTW, if you're using Xcode 6.2, that predates Swift 1.2 which was introduced with Xcode 6.3, so you're limited to some of the less elegant struct solutions in that article you reference.

For the record, using singletons to gain access to model data throughout the app is intoxicatingly simple, but as rmaddy suggested, this practice is generally discouraged. As apps get more complicated, it starts to introduce subtle maintenance issues. It's not a good habit to adopt. This is, admittedly, a subject of some debate, so I will instead refer you to What is so bad about singletons?, rather than starting the conversation again here.

Community
  • 1
  • 1
Rob
  • 371,891
  • 67
  • 713
  • 902