Search code examples
swiftdictionaryswift2gameplay-kit

"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?


Solution

  • 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