Swift 声明私有变量时结构编译器错误

Swift struct compiler error when declaring a private var

我有一个非常简单的 struct 可以按预期工作:

struct Obligation {
    
    var date = Date()
}

let snapshotEntry = Obligation(date: Date())

但是,如果我向该结构添加私有变量,我会在创建结构实例的行中收到编译错误,提示为 Argument passed to call that takes no arguments:

struct Obligation {
    
    var date = Date()
    
    private var blank:Bool = false
}

let snapshotEntry = Obligation(date: Date())

如果我从新的 blank 变量中删除 private,它可以正常编译。 我在这里忽略了一些简单的事情吗? struct 可以没有私有变量吗?

您不能使用默认成员明智 initialiser 分配 struct's 属性 访问级别 private modifier.If 您需要分配您的私人 属性 使用 initializer,你必须自己编写或给私有成员初始化值来解决它

正如 Access Control 文档明确指出的那样:

The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Likewise, if any of the structure’s stored properties are file private, the initializer is file private. Otherwise, the initializer has an access level of internal.

只需使用自定义初始化程序。

这应该有效:

struct Obligation {
    var date: Date
    private var blank: Bool
    
    init(date: Date = Date(), blank: Bool = false) {
       self.date = date
       self.blank = black
    }
}
    
let snapshotEntry = Obligation(date: Date())