-1

I have a viewModel file where I initialize two arrays, which are the users with type User and the lastM of type Message. Ill add in an example below of what the arrays look like when I print them out. Im trying to reference these arrays in a view file. On init the view gets a user passed to it. By taking the user passed into the view I am trying to look for this users index in the Users array. Then I want to take that index and get the element in the same index in the lastM array. Every time I do this I get fatal error index out of range.

view file

    let user: User
    @ObservedObject var viewModel = MessageViewModel()
    var body: some View {
        HStack(spacing: 20){
            let index = viewModel.users.firstIndex(of: user)
            let value = viewModel.lastM[index ?? 0]

            Text(value.text)
            Text("\(value.timestamp)")

arrays in viewModel file

    @Published var users = [User]()
    @Published var lastM = [Message]()

printing out the users array looks like this:

[App.User(_id: FirebaseFirestoreSwift.DocumentID<Swift.String>(value: Optional("uosdPla4v6Mh7ZDL9lyzeqkHVOx1")), username: "baileys", fullname: "Hailey stein", profileImageUrl: "", email: "Stacymc@gmail.com"), ... more users]

printing out the lastM array looks like this:

[App.Message(id: "A7F26B3F-6F0A-4A28-8426-411149942733", text: "Hi", recieved: false, timestamp: 2022-12-18 22:46:19 +0000), ... more messages]

  • when your `index` is nil, you have `viewModel.lastM[0]` and that is out of range when `lastM` is empty (as it is initially), because element zero is not present in an empty array. – workingdog support Ukraine Dec 18 '22 at 23:23
  • @workingdogsupportUkraine I only added in ?? 0 because it was giving me an error of "Value of optional type 'Array.Index?' (aka 'Optional') must be unwrapped to a value of type 'Array.Index' (aka 'Int')" –  Dec 18 '22 at 23:26
  • @workingdogsupportUkraine how do fix it so I dont have to add in the ?? 0 –  Dec 18 '22 at 23:27
  • try this: `if let index = viewModel.users.firstIndex(of: user) { let value = viewModel.lastM[index] // do something }` – workingdog support Ukraine Dec 18 '22 at 23:29
  • SWIFT is not the same thing as Swift. –  Dec 19 '22 at 00:02

1 Answers1

1

try something like this, to avoid the ...error index out of range:

        if let index = users.firstIndex(of: user), index < lastM.count {
            let value = viewModel.lastM[index]
            Text(value.text)
            Text("\(value.timestamp)")
        } else {
            Text("no user")
        }