Jonnny Jonnny -4 years ago 94
Swift Question

for in loop not updating elements

I'm sure this is really simple. But I'm not sure what's going on. I've taken a break from swift and just getting back into it with Swift three.

I'm expecting when the play button is clicked and the

isPlaying
is true that the people in my
currentLineup[0]
have their values updated. Which they do seem to do when the function is called. But when I call
currentLieneup[0][0]
the values seem to be back to
isPlaying: false, timeCameOn: 0
as noted in the log?

I have a the following:

var currentLineup: [[Player]] = []

@IBAction func playPause(_ sender: UIButton) {
// change icon to play or pause
isPlaying = isPlaying ? false : true
// set player.timeCameOn to current time or back to 0
updatePlayerGameStartTime(gameInProgress: isPlaying)
print(currentLineup[0][0])
}

// When play button pressed, make sure players timeCameOn updated
func updatePlayerGameStartTime(gameInProgress: Bool){
if gameInProgress {
for var player in currentLineup[0]{ // Playing
player.isPlaying = true
player.timeCameOn = Int(Date().timeIntervalSince1970)
print(player)
}

for var player in currentLineup[1]{ // Subs
player.isPlaying = false
player.timeCameOn = 0
}
}
}


I note in my log the following:

Player(name: "Player 1", isPlaying: true, timeCameOn: 1488304289, currentPlayedTime: 0)
Player(name: "Player 2", isPlaying: true, timeCameOn: 1488304289, currentPlayedTime: 0)
Player(name: "Player 3", isPlaying: true, timeCameOn: 1488304289, currentPlayedTime: 0)
Player(name: "Player 4", isPlaying: true, timeCameOn: 1488304289, currentPlayedTime: 0)
Player(name: "Player 1", isPlaying: false, timeCameOn: 0, currentPlayedTime: 0)


updated
I'm setting the initial
currentLineup
by calling in viewdidload() a function called
createInitialCurrentPlayingList()
.

createInitialCurrentPlayingList(listOfPlayers: [Player]){
for player in listOfPlayers {
if startingLineup.count < 4 {
startingLineup.append(player)
} else {
startingSubs.append(player)
}
}
currentLineup.insert(startingLineup, at:0)
currentLineup.insert(startingSubs, at: 1)
}

// declarations of vars
startingLineup: [Player] = []
startingSubs: [Player] = []
currentLineup: [[Player]] = []

Answer Source

It's most likely a value type issue

Please try this, it assigns the subarray back to currentLineup.

var firstLineup = currentLineup[0]
for player in firstLineup { // Playing
      player.isPlaying = true
      player.timeCameOn = Int(Date().timeIntervalSince1970)
      print(player)
}
currentLineup[0] = firstLineup
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download