Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Swift Singleton

I've got the following Singleton class:

class Singleton {
    static let sharedInstance = Singleton()
}

I can find very little online about how to use the numerous swift implementations of the Singleton pattern. I have used it before in Objective-C on a previous application but to me it seemed much more straight forward.

For instance, if I wanted to create an array of custom objects that could be used anywhere in the application, how would I declare it, and how would I implement it. In my objective-C Singleton class, I create global variables in the class file, and then implement it like so:

singletonClass *mySingleton = [singletonClass sharedsingletonClass];
mySingleton.whatever = "blaaaah"

I appreciate the help! Also I'm new around here and new to Swift.

like image 482
Alex Cauthen Avatar asked Sep 01 '25 10:09

Alex Cauthen


1 Answers

There is a lot of info available on singletons in Swift. Have you come across this article with your Google prowess? http://krakendev.io/blog/the-right-way-to-write-a-singleton

But to answer your question, you can simply define anything you'd like to use normally.

class Singleton {
    static let sharedInstance = Singleton() // this makes singletons easy in Swift
    var stringArray = [String]()

}

let sharedSingleton = Singleton.sharedInstance

sharedSingleton.stringArray.append("blaaaah") // ["blaaaah"]

let anotherReferenceToSharedSingleton = Singleton.sharedInstance

print(anotherReferenceToSharedSingleton.stringArray) // "["blaaaah"]\n"
like image 196
Andrew Sowers Avatar answered Sep 04 '25 05:09

Andrew Sowers