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))
}
}
}
2
Answers
ForEach
with an index-based approach is dangerous in SwiftUI. Instead, make your model identifiable.Then, change your loop:
Unrelated to this exact issue, but generally SwiftUI does better with using a
struct
for a model instead of aclass
. If aUser
infriends
is updated with your current code, because it’s a nestedObservableObject
, yourView
will not get automatically updated.User
should be a struct andForEach
isn’t a traditional loop, it’s a View that must be supplied identifiable data, e.g.