Why synthesized init cannot initialize private var/let?

struct Foo {
    // 1) error: 'Foo' initializer is inaccessible due to 'private' protection level
    private var bar: Int

    // 2) this makes synthesized init work, but it should be "private", not "readable"
//    private(set) var bar: Int

    // 3) so must hand write init
    init(bar: Int) {
        self.bar = bar

let foo = Foo(bar: 100)

seems overly restrictive.

My understanding is that the synthesized init relies on the fact that var bar is a piece of API of at least the same access level. If the initializer persists in a part of the codebase while var bar gets removed, this introduces an unexpected contractual obligation: the author of Foo will be required to continue supporting an initializer that has nothing more to do with the accessible properties. In other words, the synthesized init is sort of an indication of what properties a given struct has, and semantically it's simply a function that assigns them some initial value. It otherwise would be very vague what that argument in the initializer is for.

Which is possibly indeed too restrictive for an initializer of the internal access level; perhaps it's not that necessary in that case, but I'm not sure.


Ok. Makes sense that private should not leak out.

Would be nice if private var/let can be annotated as @initializable to allow synthesized init initializations.

Terms of Service

Privacy Policy

Cookie Policy