Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 563
Nicolas Gimelli Avatar asked Jun 18 '26 21:06

Nicolas Gimelli


1 Answers

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)
like image 169
Asperi Avatar answered Jun 21 '26 11:06

Asperi