swift - 为什么我们应该在单例模式中使用结构和类函数?

标签 swift singleton

我正在阅读 Udacity 学习资料中的代码。老师用 struct 创建了一个实例变量 sharedInstance 并包裹在 class function

为什么我们不能简单地创建一个static var

class BugFactory() {
    class func sharedInstance() -> BugFactory {      

        struct Singleton {
            static var sharedInstance = BugFactory()
        }      

        return Singleton.sharedInstance
    }
}

为什么不推荐:

class BugFactory() {
    static var sharedInstance = BugFactory()
}

最佳答案

实际上,由于 swift 版本的改进,建议使用您的第二个代码。您应该考虑的另一件事是使用 static let 声明您的单例对象,并进行初始化私有(private)的

class Bar{

    private init(){
        // initialization
    }

    static let shared = Bar()

}

关于swift - 为什么我们应该在单例模式中使用结构和类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45542045/

相关文章:

swift - 如何从 Braintree Payments php 获取 header 响应

ios - 类型 'String' 不符合协议(protocol) 'NSCopying' 向下转换 AnyObject 到 String 时出错

ios - 从 Storyboard连接到 Swift View Controller 文件的 UITextField 输入

ios - CloudKit 中的记录不能超过 100 条

java - 多个线程在单例类中使用相同对象的影响

java - 接口(interface)中方法的参数(没有泛型)?

swift - class_copyMethodList 不适用于 Swift 类

ios - Singleton 类 swift 返回其属性 nil?

python - 在 Python 中与 Singleton 共享 Declarative_Base (SQLAlchemy)

design-patterns - 单态与单态