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

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.