Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over a NSSet - SwiftUI 2.0

I am starting to look at CoreData and have two entities. These form a many to many relationship between Player:

enter image description here

and Team:

enter image description here

I am trying to iterate through the players of a team using a ForEach inside a list but I can't seem to get it to work. The code I have been trying is below. Any other solutions I try I get errors such as 'Value of type NSObject has no member name'

struct PlayersView: View{
    var team: Team
    
    var body: some View{
        NavigationView{
            List{
                ForEach(Array(team.people! as Set), id: \.self){ player in
                    Text("\(player.name)" ) //Error on this line
                    
                }
            }
        }
    }
}

Any ideas? I think I need to change the player type back to the Player Object but I am not sure

like image 635
benpomeroy9 Avatar asked Dec 30 '22 17:12

benpomeroy9


1 Answers

Try the following (compiled with Xcode 12.1 / iOS 14.1)

ForEach(Array(team.people as? Set<Player> ?? []), id: \.self){ player in
    Text("\(player.name ?? "")" )
}

Caution: try to avoid force unwrapping for optionals, very often it will result in run-time crash.

like image 109
Asperi Avatar answered Jan 10 '23 16:01

Asperi