I am trying to return a class type in my swift code, but no matter what code I try I keep getting endless error for optional, below is my code that checks if an id is inside a class and matched with id in another class I should return that user... below is my code and CoreData relationship....
I keep getting error - in Friends section
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
How can I return the user that matches the friend in list ? please guide , thanks
//-----Code
import SwiftUI
struct DetailView: View {
let user: CachedUser
@State private var users = [CachedUser]()
@State private var friends = [CachedFriend]()
var body: some View {
Form {
List {
Section("Name") {
Text(user.wrappedName)
.font(.body)
}
Section("email") {
Text(user.wrappedEmail)
}
Section("Registration Date") {
Text(user.wrappedEmail)
}
Section("Company") {
Text(user.wrappedCompany)
}
Section("Is Active") {
Image(systemName: user.isActive ? "checkmark.circle.fill" : "xmark.octagon.fill")
.foregroundColor(user.isActive ? Color.green : Color.red)
}
Section("Friends") {
ForEach(user.cachedFriend) {item in
NavigationLink {
DetailView(user: users.first(where: { itemFriend in
itemFriend.id == item.id
})! ) // <-------ERROR
} label: {
Text(item.wrappedName)
}
}
}
}
}
}
}
//-----
CodePudding user response:
I am not sure exactly what you are trying to do but why not have an if
condition around the NavigationLink
if let friend = users.first(where: { itemFriend
itemFriend.id == item.id
}) {
NavigationLink { …
//pass friend to your view instead
}