我有以下单例类:
class Singleton {
static let sharedInstance = Singleton()
}
我在网上几乎找不到关于如何使用单例模式的大量快速实现的信息。我之前在 Objective-C 中的一个应用程序中使用过它,但对我来说它似乎更直接。
例如,如果我想创建一个可以在应用程序中的任何地方使用的自定义对象数组,我将如何声明它以及如何实现它。在我的 objective-C Singleton 类中,我在类文件中创建全局变量,然后像这样实现它:
singletonClass *mySingleton = [singletonClass sharedsingletonClass];
mySingleton.whatever = "blaaaah"
感谢您的帮助!我也是这里的新手,也是 Swift 的新手。
最佳答案
有很多关于 Swift 中单例的信息。你有没有用你的谷歌实力看到这篇文章? http://krakendev.io/blog/the-right-way-to-write-a-singleton
但要回答您的问题,您可以简单地定义您想要正常使用的任何内容。
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"
关于swift - 使用 Swift 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865278/