0

I'm looping through an array of basketball players where their id is equal to a certain player's id. Then i want to add +1 to the fouls property of the player object.

self.match.matchState.homePlayers.first{$0.id == toPlayer.id}?.fouls += 1

I have the error

Left side of mutating operator isn't mutable: function call returns immutable value

The fouls property is an optional integer. var fouls: int? Even when i changed the Player struct to a class type i have another error.

Cannot pass immutable value as inout argument: function call returns immutable value

So how am i supposed to loop in an array of objects and change a certain property in it?

Kegham K.
  • 1,589
  • 22
  • 40
  • 1
    Possible duplicate of [Cannot assign to property: function call returns immutable value](https://stackoverflow.com/questions/37113951/cannot-assign-to-property-function-call-returns-immutable-value) – Mo Abdul-Hameed Oct 17 '18 at 21:32
  • @MoAbdul-Hameed i saw this question before but even though when i change the `Player` struct to a class i still have the same issue. – Kegham K. Oct 17 '18 at 21:38
  • It shouldn't give you that error using a class.. Here is a simple example: `class Player { let id: Int var fouls: Int init(id: Int, fouls: Int) { self.id = id self.fouls = fouls } } let player1 = Player(id: 1, fouls: 2) let player2 = Player(id: 1, fouls: 3) let player3 = Player(id: 1, fouls: 4) let homePlayers = [player1, player2, player3] homePlayers.first{$0.id == 1}?.fouls += 1` – Mo Abdul-Hameed Oct 17 '18 at 21:42
  • Just change `Player` to a class and make sure `fouls` is not a constant. – Mo Abdul-Hameed Oct 17 '18 at 21:45
  • Fouls is not a constant it is `var fouls: Int?` but wait the error this time i think it's different. "Cannot pass immutable value as inout argument: function call returns immutable value" there is the inout issue. – Kegham K. Oct 17 '18 at 21:46
  • If you were trying to pass a `Player` instance anywhere in your code as an `inout` parameter you should now remove the `inout` keyword. – Mo Abdul-Hameed Oct 17 '18 at 22:01

1 Answers1

0

I changed Player type from struct to class then i found a way around to updated the Player object fouls property this way and it is working fine now with no errors

if toPlayer.fouls == nil {
   self.match.matchState.homePlayers.first{$0.id == toPlayer.id}?.fouls = toPlayer.fouls! + 1
}
Kegham K.
  • 1,589
  • 22
  • 40