0

I'm not quite understanding why the following code does not update the original values of array1 and array2. I'm trying to use inout on an array of iVars ...

import UIKit

class ViewController: UIViewController {

    // MARK: instance variables

    var array1: [Int] = [1, 1, 1]
    var array2: [Int] = [2, 2, 2]



    // MARK: lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()

        var tempArray = [array1, array2]
        performOperationOn(&tempArray)
        print("array1: \(array1)")
        print("array2: \(array2)")
        print("tempArray[0]: \(tempArray[0])")
        print("tempArray[1]: \(tempArray[1])")
    }



    // MARK: private methods

    private func performOperationOn(_ array: inout [[Int]]) {
        array[0][0] = 11
        array[0][1] = 11
        array[0][2] = 11

        array[1][0] = 22
        array[1][1] = 22
        array[1][2] = 22
    }
}

...

The above prints out:

array1: [1, 1, 1]
array2: [2, 2, 2]

Is there any way to accomplish what I'm expecting:

array1: [11, 11, 11]
array2: [22, 22, 22]

Printing out tempArray does reveal it is being modified:

tempArray[0]: [11, 11, 11]
tempArray[1]: [22, 22, 22]

But I really want the OG arrays (array1 and array2) to be the ones being modified ... thoughts?

Chris Allinson
  • 1,837
  • 2
  • 26
  • 39
  • 1
    `tempArray` copies the contents of `array1`, `array2` – Alexander Oct 10 '18 at 20:10
  • ok right, Int is a value-type ... interestingly enough, in my actual app I simply changed from a struct to a class and the "Ints" in my above example actually do update and all is well! Thanks for this hint :) – Chris Allinson Oct 10 '18 at 20:20
  • 1
    It's called *copy-on-write* – ielyamani Oct 10 '18 at 20:24
  • 1
    @ChrisAllinson What exactly is your usecass here? Using `inout` variables as a substitution for assignment is an anti-pattern. – Alexander Oct 10 '18 at 22:20
  • @Alexander I'm building a game where I'm trying to simply mark elements in a multidimensional array as "winning" based on some matching logic. So, I'm initially thinking here to pass in my array of arrays to a worker and have it simply return me the same dataset but with "winning" flags flipped for those who match etc. ... have another design pattern I could use? In passing, I refactored my code to not use the class approach which is nice ... I am returning myself copied data, then overriding array1/array2 with it. – Chris Allinson Oct 10 '18 at 22:35
  • 1
    @ChrisAllinson It's not a view controller's job to manage a game board's state. Make a `GameBoard` struct, with mutating functions that flip flags, clears the board, sets the board values, etc. – Alexander Oct 10 '18 at 22:41

0 Answers0