swift - 了解结构初始化器是否包含私有(private)属性

标签 swift struct

如果 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/

相关文章:

struct - 结构是否实现了其嵌入类型之一实现的所有接口(interface)?

c - 结构中的枚举

swift - 雪碧包 : How do you call touches began & in touches separately?

go - 更新结构中的值不起作用

ios - 在 macOS 编程中是否有 UIGraphicsGetImageFromCurrentImageContext() 的替代方法?

swift - 调用 SwiftyDropbox 方法时的 NSURLErrorDomain 代码 -999

编译时无法读取结构体枚举

c - 无效使用灵活数组 - 灵活结构数组作为另一个结构的成员

ios - Swift 3 - 无法更改我的 Cell.AccessoryView 上的背景颜色

ios - 以编程方式使用按钮上的约束,该按钮也是以编程方式制作的