Faisal Ikwal
Faisal Ikwal

Reputation: 713

Understanding struct initialiser if it contain private property

I want to understand how initialiser work if struct contains private properties. I have following code:

struct Doctor {
    var name: String
    var location: String
    private var currentPatient = "No one"
}
let drJones = Doctor(name: "Esther Jones", location: "Bristol")

This throws an error:

Cannot invoke initializer for type 'Doctor' with an argument list of type '(name: String, location: String)'

My Assumption is: Default Memeberwise initialiser contains private property which can't be called from outside.

But I am confused by following code:

struct Doctor {
    private var currentPatient = "No one"
}
let drJones = Doctor()

How this is working?, it is not throwing any error.

Upvotes: 1

Views: 693

Answers (2)

litbe
litbe

Reputation: 507

Per Swift's doc:

Default initializers

Swift provides a default initializer for any structure or class that provides default values for all of its properties and doesn’t provide at least one initializer itself.

Because your example does not provide an initializer, Swift attempts to provide a default initializer but can't due to the private member, currentPatient.

I was surprised by the error also because I'd thought the compiler would know to exclude the private members with default values.

Upvotes: 0

Robert Dresler
Robert Dresler

Reputation: 11210

You can't use default memberwise initialiser for assigning struct's property with private access level modifier.

Your second example works, because you gave your property default value so there is no need to assign it while you're initalizing it.

If you need to assign your private property using initializer, you have to write your own

init(name: String, location: String, currentPatient: String) {
    self.name = name
    self.location = location
    self.currentPatient = currentPatient
}

Upvotes: 3

Related Questions