Using the Swift Singleton

2019-07-19 17:53发布

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.

2条回答
Viruses.
2楼-- · 2019-07-19 17:58

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"
查看更多
太酷不给撩
3楼-- · 2019-07-19 18:04

Agree with Andrew Sowers. Just remember that you must also declare a private initializer like this:

class Singleton: NSObject {
    static let sharedInstance = Singleton()
    private override init() {}
}

Without this private init(), other objects could create their own instance:

let mySingleton = Singleton()

Now there are two instances, Singleton.sharedInstance and mySingleton - no longer a singleton! I discovered this via a nasty bug where multiple "singletons" were firing timers and wreaking havoc.

查看更多
登录 后发表回答