Search code examples
swiftstructxcode12

Swift struct compiler error when declaring a private var


I have a very simple struct which works as expected:

struct Obligation {
    
    var date = Date()
}

let snapshotEntry = Obligation(date: Date())

however if I add a private var to this struct, I get a compile error on the line I create an instance of my struct saying Argument passed to call that takes no arguments:

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

let snapshotEntry = Obligation(date: Date())

enter image description here

If I remove the private from the new blank var it compiles fine. Am I overlooking something simple here? Can a struct not have a private var?


Solution

  • As the Access Control documentation clearly states:

    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.

    Just use a custom initializer.