Search code examples
swiftstruct

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.


Solution

  • 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
    }