GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Problems using a View Model array

Forums > SwiftUI

getting index out of range.....

New to Swift so anyhelp would be greatly appreciated!

import SwiftUI

@Observable class ViewModule { init() {} var name = "" }

var viewModel: [ViewModule] = []

struct ContentView: View { var body: some View { VStack { Button ("Test") { viewModel[0].name = "test" //get index out of range } } } }

Preview {

ContentView()

}

2      

That because you do not have any items in the array and trying to change an item.

You need to .append(value: Hashable>) to the array in the Button action

2      

Hello. Why do you want to use an array of @Observable object?

If you want to use ViewModel, i think you should do this way:

Define a model:

struct TestData  {
  var name: String
}

Define a viewModel:

@Observable
class ViewModel {
  var testData = [TestData]()
}

in your view:

struct ContentView: View {
      @State var viewModel = ViewModel()

       var body: some View {
             Button {
                   viewModel.testData.append(TestData(name: "TestName"))
             } label: {
                 Text("Add item")
             }
       }
}

2      

How might this work if you then tried to access the same array from a second ViewModel?

   

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.