Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign to property: 'card' is a 'let' constant in a for loop in swift [duplicate]

Cannot assign to property: 'card' is a 'let' constant in for loop in chooseCard method. I am not able to figure out why the error is coming in the for loop .what am I missing in the code .Please help.

import Foundation

class Concentration {

    var cards = [Card]()

    var faceUpCount = 0

    func chooseCard(atIndex : Int) {
        var alreadyFaceUpCard  = Card()
        if faceUpCount == 0 {
            alreadyFaceUpCard = cards[atIndex]
            alreadyFaceUpCard.isFaceUp = true
            faceUpCount += 1
        }else if faceUpCount == 1 {
            var card = cards[atIndex]
            card.isFaceUp = true
            if alreadyFaceUpCard.identifier == card.identifier {
                alreadyFaceUpCard.isMatchUp = true
                card.isMatchUp = true
                faceUpCount += 1
            }

        }else {
            for card in cards {
                card.isFaceUp = false
            }

        }

    }



    init(numberOfPairsOfCards : Int) {
        for _ in 1...numberOfPairsOfCards {
            let card = Card()
            cards.append(card)
            cards.append(card)
        }
        // TODO: Shuffle Cards
    }


}
like image 362
sriram hegde Avatar asked Jan 03 '18 11:01

sriram hegde


People also ask

Is a let constant Swift?

Swift employs the keywords let and var for naming variables. The let keyword declares a constant, meaning that it cannot be re-assigned after it's been created (though its variable properties can be altered later). The var keyword declares a new variable, meaning that the value it holds can be changed at a later time.


1 Answers

card is ofcourse a let constant, to make it variable use: for var card in cards

like image 156
Madhur Avatar answered Sep 20 '22 18:09

Madhur