在 Swift 3中具有属性的单例

在苹果的 在 Cocoa 和 Objective-C 文档中使用 Swift(更新为 Swift 3)中,他们给出了以下单例模式的例子:

class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()


// setup code


return instance
}()
}

让我们假设这个单例模式需要管理一个 String 变量数组。我应该如何/在哪里声明这个属性并确保它正确地初始化为一个空的 [String]数组?

83606 次浏览

Any initialisation would be done in an init method. No difference here between a singleton and a non-singleton.

You can initialize an empty array like this.

class Singleton {


//MARK: Shared Instance


static let sharedInstance : Singleton = {
let instance = Singleton(array: [])
return instance
}()


//MARK: Local Variable


var emptyStringArray : [String]


//MARK: Init


init( array : [String]) {
emptyStringArray = array
}
}

Or if you prefer a different approach, this one will do fine.

class Singleton {


//MARK: Shared Instance


static let sharedInstance : Singleton = {
let instance = Singleton()
return instance
}()


//MARK: Local Variable


var emptyStringArray : [String]? = nil


//MARK: Init


convenience init() {
self.init(array : [])
}


//MARK: Init Array


init( array : [String]) {
emptyStringArray = array
}
}

For me this is the best way, make init private. Swift 3 \ 4 \ 5 syntax

// MARK: - Singleton


final class Singleton {


// Can't init is singleton
private init() { }


// MARK: Shared Instance


static let shared = Singleton()


// MARK: Local Variable


var emptyStringArray = [String]()


}

As per the apple's documentation: In Swift, you can simply use a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously.

class Singleton {


// MARK: - Shared


static let shared = Singleton()
}

With initialization method:

class Singleton {


// MARK: - Shared


static let shared = Singleton()


// MARK: - Initializer


private init() {
}


}