In the below code, a struct called Card
is assigned with let
. Then, once assigned, I put this card into an array. Now, in func resetCards
, I want to set each card in the array back to its original state. However, if I use a for loop for each card in the array I get an error saying "cannot assign property to constant"
, which I expect. However, If I do something like: cards[0].variable = false
, I don't get an error and I can change the struct variables. Why if I loop through an array using a for card in cards
loop I can't change the properties of the structs even if the properties are declared using var
, but if I access the structs using an array index e.g. for index in cards.indices
I can?
class Concentration {
var cards = [Card]()
init(numberOfPairsOfCards: Int) {
for _ in 0..<numberOfPairsOfCards {
let card = Card()
cards += [card, card]
}
func resetCards() {
indexOfOneAndOnlyFaceUpCard = nil
for card in cards {
card.variable = true // this doesn't work
cards[0].variable = true // this works
}
}
}