2

I have a GKGameModel that stores its internal state in an array a of Cards and a dictionary b that maps from Ints to arrays of Cards. GameplayKit mandates that I must copy this internal state in setGameModel:.

The following code is meant to just-copy the array and "deep-copy" the dictionary. FWIK this should be sufficient since Cards themselves never change.

var a: [Card]
var b: [Int: [Card]]

func setGameModel(gameModel: GKGameModel) {
    let otherGameModel = gameModel as! GameModel
    a = otherGameModel.a
    b = otherGameModel.b.map { (i: Int, cards: [Card]) in (i, cards) }
}

However, this causes the following syntax error in the line that attempt the "deep-copy":

Cannot assign a value of type '[(Int, [Card])]' to a value of type '[Int, [Card]]'.

What am I doing wrong?

Community
  • 1
  • 1
Drux
  • 11,992
  • 13
  • 66
  • 116
  • My Swift's a bit rusty when it comes to literals, but like vadian said, this `(i: Int, cards: [Card]) in (i, cards)` defines an array but you want a dictionary which would use the other brackets: `[i: Int, cards: [Card]] in [i, cards]`. Syntax may not be correct but the issue is something along that line ... – CodeSmile Aug 20 '15 at 11:42

2 Answers2

2

In your case:

b = otherGameModel.b

is sufficient.

Because, Array and Dictionary are both value types. So when it is assigned to another variable, it will be deep copied.

var bOrig: [Int: [Int]] = [1: [1,2,3], 2:[2,3,4]]
var bCopy = bOrig

bCopy[1]![2] = 30

bOrig[1]![2] // -> 3
bCopy[1]![2] // -> 30
rintaro
  • 51,423
  • 14
  • 131
  • 139
1

The error message reveals there is a type mismatch:

variable b is declared as Dictionary<Int,[Card]> but the map function returns an Array of tuplets (Int, [Card])

vadian
  • 274,689
  • 30
  • 353
  • 361
  • So can this be solved with `map()` or is there a better alternative? – Drux Aug 20 '15 at 11:37
  • No, because a `Dictionary` does not respond to `map()`. You might use an enumerator. – vadian Aug 20 '15 at 11:41
  • I'll try this replacement for the offending line: `b = [:]; for (i, cards) in otherGameModel.b { hands[i] = cards }` – Drux Aug 20 '15 at 11:57