Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
Darren Avatar asked Dec 19 '25 10:12

Darren


2 Answers

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.

like image 179
gcharita Avatar answered Dec 21 '25 01:12

gcharita


You can't use default member wise initialiser for assigning struct's property with private access level modifier.If you need to assign your private property using initializer, you have to write your own OR give private member initiate value resolves it

like image 36
Jawad Ali Avatar answered Dec 21 '25 02:12

Jawad Ali