With the release of Swift 1.2, initializing a singleton class has become incredibly succinct using the class constant approach. I know what you’re thinking, “Singleton? Globals are bad!”

I feel the fundamentally the same way. However, sometimes in simple and personal projects, using a singleton pattern is the simplest solution.

This past weekend, I was porting some Objective-C  to Swift for one of my favorite open source projects, AudioKit.io.

This was the Objective-C code:

+ (SharedStore *)globals
    // the instance of this class is stored here
    static SharedStore *globals = nil;
    // check to see if an instance already exists
    if (nil == globals) {
        globals  = [[[self class] alloc] init];
    // return the instance of this class
    return globals;

Using the new recommended class constant approach, that code can now be replaced with just one line:

static let globals = SharedStore()

To learn more about the evolving history of Singletons in Swift, check out this repository:

You can learn more and download my project at:

 App Development, Apps, Development

, , , ,

Matthew's Blog
Home   Blog   LinkedIn   Contact Me
Connect on LinkedIn, Google+,
Current focus: App & Web Development
Preferred Environments: OS X, iOS, Xcode, Sublime Text
Current skills: SWIFT, Objective-C, iOS SDK, CoreData, CoreAudio, JavaScript, HTML5, CSS, Wordpress
Degree: Bachelors of Science in Computer Information Systems Technology
from PURDUE University

© Website by Matthew Fecher
Denver, Colorado, USA.