Although my initial problem was solved on StackOverflow(Link Here), I'm still messing around this issue and can't find reasonable answer why property can't be overriden in init() if initial value is set. Here is entire code:
import SwiftUI
struct ContentView: View {
@State var bits: Int64 = 5
var body: some View {
Form {
Section {
SectionView(title: "Section", withBits: $bits)
} header: {
Text("Toggle")
}
}
}
}
struct SectionView: View {
let title: String
@Binding var bits: Int64
@State private var first: Bool = false
@State private var second: Bool = false
@State private var third: Bool = false
init(title: String, withBits: Binding<Int64>) {
self.title = title
self._bits = withBits
// below three lines are completely ignored when they have initial value
self.first = withBits.wrappedValue & 1 == 1
self.second = withBits.wrappedValue & 2 == 2
self.third = withBits.wrappedValue & 4 == 4
}
var body: some View {
VStack {
HStack {
Text(self.title)
}
HStack {
Toggle("Toggle 1", isOn: self.$first)
.onChange(of: self.first) { newValue in
if newValue {
self.bits |= 1
}
else {
self.bits &= ~1
}
}
}
HStack {
Toggle("Toggle 2", isOn: self.$second)
.onChange(of: self.second) { newValue in
if newValue {
self.bits |= 2
}
else {
self.bits &= ~2
}
}
}
HStack {
Toggle("Toggle 3", isOn: self.$third)
.onChange(of: self.third) { newValue in
if newValue {
self.bits |= 4
}
else {
self.bits &= ~4
}
}
}
}
.onChange(of: self.bits) { newValue in
print("bits: \(bits)")
}
}
}
If I remove property initialization as below then works:
@State private var first: Bool
@State private var second: Bool
@State private var third: Bool
Could anyone explain why above code won't work? I'm now kinda worry about my old code that I always set initial value to properties to avoid garbage in them so.
Did you read this one ?
or this, with similar advice
If I understand well, they suggest to call:
self._first = State(wrappedValue: withBits.wrappedValue & 1 == 1)