Im trying to use properties of @State var
and @Binding var
variables in the initialization process of my View but I don’t really understand if the way im doing it is a conventional or “legit” way of doing it or if it’s just that i can’t do it the “legit” way because i dont understand how @State var
and @Binding var
works.
This is what im currently doing
struct EditPrView: View {
@State var name: String
@State var nameCount: Int = 0 // Some value just to initalise the variable
var body: some View {
VStack {
Text(name)
Text(String(nameCount))
}.onAppear(perform: { // Do the "actual" assigment here
nameCount = name.count
})
}
}
This works well (i havent run in to issues yet) but it feels “hacky” and i feel like this should be able to be done in the initialization phase of the view.
This is what i have tried
struct EditPrView: View {
@State var name: String
@State var nameCount: Int = name.count // This will throw an error
var body: some View {
VStack {
Text(name)
Text(String(nameCount))
}
}
}
This obviously doesn’t work and you get a compile time error immediately
class A {
var a: Int = 0
}
class B: A {
var b: Int = 5
}
struct EditPrView: View {
@State private var obj: A?
@State private var count: Int
init(obj: A?) {
self.obj = obj
if obj is B {
self.count = 2
} else {
self.count = 1
}
}
var body: some View {
VStack {
Text("foo-bar")
Text(String(count))
}
}
}
#Preview {
var b: A? = B()
return EditPrView(obj: b)
}
This works fine while im only using @State
in a view
class A {
var a: Int = 0
}
class B: A {
var b: Int = 5
}
struct EditPrView: View {
@Binding private var obj: A?
@State private var count: Int
init(obj: Binding<A?>) {
self._obj = obj
self.count = 0
if self.obj is B {
self.count = 2
} else {
self.count = 1
}
}
var body: some View {
VStack {
Text("foo-bar")
Text(String(count))
}
}
}
#Preview {
@State var b: A? = B()
return EditPrView(obj: $b)
}
But then i try to add a @Binding var
like this and it’s like it doesnt even get to the else
statement, it just sets self.count
to 0 and then continues makes the view appear even if the instance clearly is of type B.
Since i want one way of doing view initialization this has made me stick to the .onAppear(perform: )
way of initalizing variables but as the question asks, is this really the way to do it?
TLDR
Why doesnt the if statement in the last code-block example fire?