If i don't have an initial value for a @State
and set it in the init
I get a Fatal Error: EXC_BAD_ACCESS, but only in Release Mode
public struct TestSetStateView: View {
@State var item:Int
public init(item: Int) {
self.item = item
}
public var body: some View {
Text("Hello: \(item)")
}
}
If i add a default value
public struct TestSetStateView: View {
@State var item:Int = 0
public init(item: Int) {
self.item = item
}
public var body: some View {
Text("Hello: \(item)")
}
}
and call it with TestSetStateView(item: 8)
it shows "Hello: 0"
If I move that to onAppear
public struct TestSetStateView: View {
@State var item:Int = 0
let firstItem: Int
public init(item: Int) {
firstItem = item
}
public var body: some View {
Text("Hello: \(item)")
.onAppear(perform: {
item = firstItem
})
}
}
and call it with TestSetStateView(item: 8)
it shows "Hello: 8" which is great
or if i use the _
wrapper:
public struct TestSetStateView: View {
@State var item:Int
public init(item: Int) {
_item = State(initialValue: item)
}
public var body: some View {
Text("Hello: \(item)")
}
}
and call it with TestSetStateView(item: 8)
it shows "Hello: 8", which is also great!
I'm just not sure what's happening, why can i use item = firstItem
in onAppear
and not in init
. I sort of understand that the _
uses the @State
wrapper but why don't we have to use the in onAppear.
Also not sure why the error in the first example only happens in release.