使用 Swift 单例 [英] Using the Swift Singleton
问题描述
我有以下单例类:
class Singleton {
static let sharedInstance = Singleton()
}
我在网上几乎找不到关于如何使用单例模式的众多 swift 实现的信息.我之前在 Objective-C 中的一个以前的应用程序中使用过它,但对我来说它似乎更直接.
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.
例如,如果我想创建一个可以在应用程序的任何地方使用的自定义对象数组,我将如何声明它,以及如何实现它.在我的 Objective-C Singleton 类中,我在类文件中创建了全局变量,然后像这样实现:
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"
感谢您的帮助!此外,我是这里的新手,也是 Swift 的新手.
I appreciate the help! Also I'm new around here and new to Swift.
推荐答案
有很多关于 Swift 中的单身人士的信息.你有没有用你的谷歌实力读过这篇文章?http://krakendev.io/blog/the-right-way-to-write-a-singleton
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"
这篇关于使用 Swift 单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!