Marking member private results in Argument Passed to Call That Takes No Arguments

Viewed 38

Compiles:

struct Foo {
    var g: Double = 5.0
}

struct Bar {
    var h: Double = 5.0
    var foo = Foo()
}

var bar = Bar(h: 6)

Add "private" and no longer compiles, with above error in title:

struct Foo {
    var g: Double = 5.0
}

struct Bar {
    var h: Double = 5.0
    private var foo = Foo()
}

var bar = Bar(h: 6) // compiler error on this line

Why would that be?

1 Answers

This is because for a struct a synthesised memberwise init will be private if any of its members are private. So instead you will get an init without arguments since all properties has default values (if at least one property that is non-optional lacks a default value no init will be synthesised at all).

From the Swift Programming Language book

The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Likewise, if any of the structure’s stored properties are file private, the initializer is file private. Otherwise, the initializer has an access level of internal.

So in your case you will need to write a custom init for your struct

Related