I dont understand why line # code is wrong. the private property is initialized with string value inside struct already so it does not need to be initialized again in line #, isn't it?
A memberwise initializer will still be synthesized for var
properties that have a default value. But not for let
properties with a default value. This is because a let
can't be changed once it has a value but a var
can be changed. You can omit a value that has a default when you are initializing, but technically it's still there.
But if that property also has a private
access level, then the compilar can't synthesize an initializer and you have to supply it explicitly.
struct Doctor {
var name: String
var location: String
private var currentPatient = "No one"
}
let doc = Doctor(
Will generate the error 'Doctor' initializer is inaccessible due to 'private' protection level
But if you select Doctor
in the struct name and use the Generate memberwise initializer feature found under Editor > Refactor, you get this:
struct Doctor {
internal init(name: String, location: String, currentPatient: String = "No one") {
self.name = name
self.location = location
self.currentPatient = currentPatient
}
var name: String
var location: String
private var currentPatient = "No one"
}
and now let doc = Doctor(
will prompt you with two autocomplete options: