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