'Thread 1: Fatal error: Index out of range In SwiftUI

i am trying to make a small Social Media app. the friends and friendrequest gets stored as User in different arrays. But when i want to loop the array it an shows which user send a request it first works but when i accept the user and he is remove from the Array i am getting this error "Thread 1: Fatal error: Index out of range" i know its because the loop wants to loop to a index which doesn't exist anymore but how do i fix it ?

struct FriendsView: View {

@EnvironmentObject var appUser: User

var body: some View {
    
List {
    ForEach(0..<appUser.friendAnfrage.count) {
    durchlauf in
        SingleFriendView(user: appUser.friendAnfrage[durchlauf])
            }
        }
    }
}

class User: ObservableObject{

@Published var username: String = ""
@Published var name: String = ""
var password: String = ""
@Published var email: String = ""
@Published var beschreibung: String = ""
@Published var profilBild: UIImage?

@Published var friends = [User]()
@Published var friendAnfrage = [User]()
@Published var anfrageGesendet = [User]()

@Published var feed = [SinglePostView]()

func addFriend(friend: User,appUser: User) {
    friend.friendAnfrage.append(appUser)
    appUser.anfrageGesendet.append(friend)
    
}
func newFriend(newFriend: User) {
    friends.append(newFriend)
    
    for i in 0..<friendAnfrage.count {
        if friendAnfrage[i].username == newFriend.username {
            friendAnfrage.remove(at: i)
        }
    }
}
func friendAnfrage(friend: User,appUser: User) {
    appUser.friendAnfrage.append(friend)
}

func makePost(image: UIImage,appUser: User) {
    
    feed.append(SinglePostView(bild: image, ersteller: appUser))
    
    for i in 0..<friends.count {
        friends[i].feed.append(SinglePostView(bild: image, ersteller: appUser))
    }
}

}



Solution 1:[1]

User should be a struct and ForEach isn't a traditional loop, it's a View that must be supplied identifiable data, e.g.

struct FriendsView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        List {
            ForEach($model.users) { $user in
                SingleFriendView(user: $user)
            }
        }
    }
}

struct User: Identifiable{
    let id = UUID()
    var username: String = ""
    var friends: [UUID] = []
}

class Model: ObservableObject {
    @Published var users: [User] = []
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1