2

I'm trying to use an array to display some game info whenever an array gets updated by a call to a web service. The array is populating fine, but at runtime I get:

Generic struct 'ForEachWithIndex' requires that 'Binding<[MatchData]>' conform to 'RandomAccessCollection'

My ScrollView:

ScrollView{
    ForEach(GameCenterHelper.helper.$MatchList, id: \.self) {row  in
           ext("\(row.id)")
    }
}

My declaration of the array:

@State var MatchList: [MatchData] = [MatchData]()

And MatchData:

class MatchData : Identifiable {
    
var id: String

var LocalPlayer: Player
var RemotePlayer: Player

init(_ match: GKTurnBasedMatch) {
    
    let local = match.participants[0].player!
    let remote = match.participants[1].player ?? GKPlayer()
    self.id = match.matchID
    
    LocalPlayer = Player(Alias: local.alias
        , DisplayName: local.displayName
        , TeamPlayerId: local.teamPlayerID
        , PlayerId: local.gamePlayerID
    )
    
    RemotePlayer = Player(Alias: remote.alias
        , DisplayName: remote.displayName
        , TeamPlayerId: remote.teamPlayerID
        , PlayerId: remote.gamePlayerID
        
    )
}
}

I have to admit, this is the first time I've used state to try and refresh a ScrollView, but I am finding it much harder than I expected and I am not sure what I have gotten wrong in my code.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Gavin Beard
  • 69
  • 1
  • 9

1 Answers1

0

You don't need binding to iterate MatchList in ForEach, access it directly

ScrollView{
    ForEach(GameCenterHelper.helper.MatchList, id: \.self) {row  in // << no $
           ext("\(row.id)")
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thank you, that gets rid of the error, but the list still doesn't update when new elements are added to the array. Hopefully I'll figure that big, I wonder if it is because the @state is in another struct – Gavin Beard Aug 09 '20 at 09:44
  • This is a different question and not to provided code - it is somewhere in service implementation where MatchList is updated with MatchData – Asperi Aug 09 '20 at 09:51