Home > other >  SwiftUI - State Bool Array not appending in init() function
SwiftUI - State Bool Array not appending in init() function

Time:02-17

I'm attempting to use a for-loop to set the values of a Bool array in SwiftUI as follows:

@State var expanded: [Bool] = []

init() {
  for i in 0..<5 {
    expanded.append(false)
  }

  print(expanded)
}

However, the print statement only prints [], and the array seems to be empty. Could anyone explain why the array is not being appended to and how I can fix this?

CodePudding user response:

You cannot do that with State, create and initialize instead, like

@State var expanded: [Bool]

init() {
  var values: [Bool] = []
  for i in 0..<5 {
    values.append(false)
  }

  print(values)
  _expanded = State(initialValue: values)    // << here !!
}

or better

@State var expanded: [Bool] = Array(repeating: false, count: 5)
  • Related