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

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 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.