TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Non-constant range: not an integer range while enumerating an array of arrays... why?

Forums > SwiftUI

I have this code


  let firstRow = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]
  let secondRow = ["a", "s", "d", "f", "g", "h", "j", "k", "l"]
  let thirdRow = ["z", "x", "c", "v", "b", "n", "m"]
  let fourthRow = ["space"]

  let allRows:[[String]]

  init() {
    self.allRows = [firstRow, secondRow, thirdRow, fourthRow]
  }

then this other code:

  var body: some View {
    VStack(spacing: 9) {
      ForEach(allRows.indices) { row in
        let num = allRows[row].indices
        HStack(spacing: 0) {
          ForEach(num) { column in
            Button(action: {}) {
              Text(keyboardViewModel.allRows[row][column])
                .font(.system(size: 15, weight: .regular, design: .default))
                .foregroundColor(.white)
                .buttonStyle(PlainButtonStyle())
                .frame(width: keyWidth)
                .background(GeometryReader {
                  Color.clear.preference(key: KeyWidthKey.self,
                                         value: $0.frame(in: .local).size.height)
                })
                .contentShape(Rectangle())
            }
          }
        }.onPreferenceChange(KeyWidthKey.self) { keyWidth = $0 }

      }
    }
  }

struct KeyWidthKey: PreferenceKey {
  static var defaultValue: CGFloat { 0 }
  static func reduce(value: inout Value, nextValue: () -> Value) {
    value = max(value, nextValue())
  }
}

The idea is to render a keyyboard with four rows of keys.

These two lines

ForEach(keyboardViewModel.allRows.indices) { row in

and

ForEach(num) { column in

give me the error

Non-constant range: not an integer range

The first error points to indices and the second one to num.

Why is that? How do I solve this?

I would like to understand the problem.

   

found the problem. Thanks to the error message, the solution has nothing to do with anything, as expected.

Just add , id: \.self to both ForEach

   

found the problem

No! You found the solution! Thanks for coming back and sharing your solution. But also, please, take a moment and mark your answer as "Solved".

   

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.