View with a binding and a private property

Hi,

I'm learning SwiftUI and there are still some things I don't understand very well.

For example, this is compiling correctly:
Code Block
struct Test: View {
    private var testPrivateProperty = 1
    var body: some View {
        Text("Test")
    }
}
struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test()
    }
}


This is also compiling correctly:
Code Block
struct Test: View {
    @Binding var testBinding: Bool
    var body: some View {
        Text("Test")
    }
}
struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test(testBinding: .constant(true))
    }
}

But if I create a View that contain both a binding and a private property:
Code Block
struct Test: View {
    @Binding var testBinding: Bool
private var testPrivateProperty = 1
    var body: some View {
        Text("Test")
    }
}
struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test(testBinding: .constant(true))
//Error on the line above.
    }
}

the compiler produce this error:

'Test' initializer is inaccessible due to 'private' protection level

Can anyone help me understand why?

Thank you



Can anyone help me understand why?

An interesting example.

When you define a struct, Swift compiler generates a memberwise initializer implicitly.
(Memberwise Initializers for Structure Types in Comparing Structures and Classes,
SE-0242 Synthesize default values for the memberwise initializer)

Something like:
Code Block
init(testBinding: Binding<Bool>, testPrivateProperty: Int = 1) {
self._testBinding = testBinding
self.testPrivateProperty = testPrivateProperty
}

It seems Swift marks this sort of initializers as private, when any of the properties are private.

You may need to define a non-private initializer yourself, when your View has any private properties.


This behavior is not explicitly stated in the articles linked above. You may send a bug report to swift.org, or start a new thread in forums.swift.org .
View with a binding and a private property
 
 
Q