I have a View struct that has two properties, both private vars, but one is a @State. Both have a default value:
struct MyView: View {
private var x: Int = 0
@State private var y = 0
. . .
}
With this, I ran into the issue of being unable to initialize that struct because of the x variable despite it having the default variable. See the bug report: `initializer is inaccessible due to 'private' protection level` error for structs with private variables with default values. · Issue #64738 · apple/swift · GitHub
This led me to think that Property Wrappers are not included in the struct's initializer, and that's why they do not cause that error since they don't affect the initializer protection level.
I'm curious, why are Property Wrappers not included in the View initializer?
1 Like
ksemianov
(Konstantin Semianov)
2
Both x and y are not included in the automatically synthesized initializer, because the variables are declared private. But you can define a custom one.
struct MyView: View {
private var x: Int = 0
@State private var y = 0
init(x: Int, y: Int) {
self.x = x
self.y = y
}
. . .
}
1 Like
rayx
(Huan Xiong)
3
FYI that I find a way to verify the signature of the private synthesized init() by using static variable and Xcode autocomplete feature.
For the issue in the bug report, the synthesized init() includes y. It doesn't compile because the init() is private:
struct Struct {
// this works
static var shared = Struct(x: 1, y: 1)
var x: Int
private var y: Int = 0
}
When y is wrapped in a property wrapper, a similar experiment shows that synthesized init() includes y only if it doesn't have default value. Otherwise it doesn't (I'm also curious why).
Here’s the pull request: Prevent less-visible properties with delegates from affecting memberwise initializer by DougGregor · Pull Request #24390 · apple/swift · GitHub
Turns out we are just being on the defensive (until a proper proposal on improving memberwise init derivation comes forth).
2 Likes