Reputation: 33036
We have struct single in our code like this:
struct Foo {
let bar: String
static let sharedInstance = Foo(bar: "blah")
}
It works nice except that caller can still initialize another instance of the Foo instance with
let foo = Foo.init(bar: "blah")
Is there a way to make the generated initializer private?
We tried explicitly define the initializer like this:
struct Foo {
let bar: String
static let sharedInstance = Foo(bar: "blah")
private init(bar: String) {
self.bar = bar
}
}
It works, but it get a bit annoying because whenever we add/change a property, we will have to modify the initializer again. I like the way that the initializer is automatically generated and we don't have to write these boiler code. Is it possible?
Upvotes: 4
Views: 7560
Reputation: 31645
If you are noticing that implementing:
struct Foo {
let bar: String
static let sharedInstance = Foo(bar: "blah")
}
is legal even without giving bar
an initial value, why? because Swift Structs have a default initializer, called the memberwise initializer:
Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values.
The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name.
Meaning that if you tried to create a new instance of Foo
struct, the compiler should -automatically- provide:
However, you can get rid of it by implementing private init()
, but you have to make sure that all stored properties have -dummy- initial values (or maybe let them optionals...) because the struct no longer has an initializer for guaranteeing that the stored properties has values.
It should be similar to:
struct Foo {
var bar: String = ""
static var shared = Foo()
private init() {}
}
Remark: I would suggest to stuck with class when implementing a singleton pattern, you might want to check this answer (Thanks to MartinR for mentioning it).
Upvotes: 1