Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable value of type [Card] only has mutating values of name append

Tags:

swift

I have a Card class and a Player class.

In my Player class I have a function that takes a [Card] array and adds a Card to it.

However, when I call...

myCardArray.append(myCard)

...I get the error

Immutable value of type [Card] only has mutating values of name append

I can't figure out why this is? Why would this be immutable?

like image 996
Brejuro Avatar asked Jul 14 '14 22:07

Brejuro


1 Answers

without more code, we can only guess what happened

sounds like you are doing something like

func addCard(_ myCardArray: [Card]) -> [Card] {
    let myCard = Card()
    myCardArray.append(myCard)
    return myCardArray
}

the problem is that myCardArray is immutable, as error message said, you can't modify it

you can declare myCardArray mutable use var

func addCard(var _ myCardArray: [Card]) -> [Card] {
    let myCard = Card()
    myCardArray.append(myCard)
    return myCardArray
}

or create a mutable copy of it

func addCard(_ myCardArray: [Card]) -> [Card] {
    let myCard = Card()
    var mutableMyCardArray = myCardArray
    mutableMyCardArray.append(myCard)
    return mutableMyCardArray 
}
like image 89
Bryan Chen Avatar answered Sep 30 '22 14:09

Bryan Chen