Swift how to make the default initializer of a `struct` private

Viewed 5721

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?

1 Answers
Related