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]