如果 struct 包含私有(private)属性,我想了解初始化程序如何工作。我有以下代码:
struct Doctor {
var name: String
var location: String
private var currentPatient = "No one"
}
let drJones = Doctor(name: "Esther Jones", location: "Bristol")
这会引发错误:
Cannot invoke initializer for type 'Doctor' with an argument list of type '(name: String, location: String)'
我的假设是:默认的 Memeberwise 初始化程序包含无法从外部调用的私有(private)属性。
但我对以下代码感到困惑:
struct Doctor {
private var currentPatient = "No one"
}
let drJones = Doctor()
这是如何工作的?它没有抛出任何错误。
最佳答案
您不能使用默认的成员初始化器来分配具有 private
访问级别修饰符的 struct
的属性。
你的第二个例子有效,因为你给了你的属性默认值,所以在你初始化它时不需要分配它。
如果你需要使用初始化器分配你的私有(private)属性,你必须自己写
init(name: String, location: String, currentPatient: String) {
self.name = name
self.location = location
self.currentPatient = currentPatient
}
关于swift - 了解结构初始化器是否包含私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55022793/