An immutable value of type [Card] has only modified append values

I have a Card class and a Player class.

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

However, when I call ...

myCardArray.append(myCard) 

... I get an error

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

I can not understand why this is so? Why would this be the same?

+6
source share
2 answers

without 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 the error message says, you cannot change 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 this file

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

Values ​​in the dictionary can be updated using this method only if the dictionary is defined using the var keyword (that is, if the dictionary is modified)
https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/Dictionary.html

0
source

Source: https://habr.com/ru/post/972212/


All Articles