Singleton with properties in Swift 3
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]()
}
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
}
}
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() {
}
}