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

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.