Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这个单例对象可以在Swift2中使用类型存储属性吗?_Swift_Singleton_Swift2 - Fatal编程技术网

这个单例对象可以在Swift2中使用类型存储属性吗?

这个单例对象可以在Swift2中使用类型存储属性吗?,swift,singleton,swift2,Swift,Singleton,Swift2,我读到创建结构或全局常量是在Swift中实现单例模式所必需的,因为“Swift不支持类型存储属性” 在Swift2中仍然是这样吗?为了我自己的利益,我正在学习如何在Swift中实现Singleton模式,不需要被告知这是一种反模式。似乎是说存储类型属性是可能的我见过的在Swift中创建单例的最佳方法如下: class SingletonClass { static let sharedInstance = SingletonClass() private init() {} //

我读到创建结构或全局常量是在Swift中实现单例模式所必需的,因为“Swift不支持类型存储属性”


在Swift2中仍然是这样吗?为了我自己的利益,我正在学习如何在Swift中实现Singleton模式,不需要被告知这是一种反模式。似乎是说存储类型属性是可能的

我见过的在Swift中创建单例的最佳方法如下:

class SingletonClass {
    static let sharedInstance = SingletonClass()
    private init() {} //This prevents others from using the default '()' initializer for this class.
}
您可以在此处阅读完整的说明:

我见过的在Swift中创建单例的最佳方法如下:

class SingletonClass {
    static let sharedInstance = SingletonClass()
    private init() {} //This prevents others from using the default '()' initializer for this class.
}
您可以在此处阅读完整的说明:

在本书的其他地方,有一节是关于单身的,我以前没有见过:

在Swift中,您可以简单地使用静态类型属性,即使跨多个线程同时访问该属性,也保证只延迟初始化一次:

class Singleton {
    static let sharedInstance = Singleton()
}
如果需要执行初始化以外的其他设置,可以将闭包调用的结果分配给全局常量:

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
        }()
}
在这本书的其他地方,有一节是关于单身人士的,我没有看到:

在Swift中,您可以简单地使用静态类型属性,即使跨多个线程同时访问该属性,也保证只延迟初始化一次:

class Singleton {
    static let sharedInstance = Singleton()
}
如果需要执行初始化以外的其他设置,可以将闭包调用的结果分配给全局常量:

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
        }()
}

是的,它是正确的,在swift中有效2@codecowboy您可以省略
,它们是多余的,不是必需的。是的,它是正确的,并且在swift中有效2@codecowboy您可以省略
,它们是冗余的,不是必需的。我要说的唯一一件事是,设计一个只能用作单例的类会导致单元测试出现问题,其中,对于每个测试,您都需要一个新的干净实例。我建议采用
NSFileManager
使用的方法,它有一个默认实例,但如果实例化也可以使用。我要说的唯一一件事是,设计一个只能用作单例的类会导致单元测试出现问题,因为每次测试都需要一个新的干净实例。我建议采用
NSFileManager
使用的方法,它有一个默认实例,但如果实例化也可以使用。