Drux
Drux

Reputation: 12670

"Deep-copy" of Swift dictionary with map()?

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?

Upvotes: 2

Views: 2682

Answers (2)

rintaro
rintaro

Reputation: 51911

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

Upvotes: 2

vadian
vadian

Reputation: 285072

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])

Upvotes: 1

Related Questions