You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24)
.
If the value is an object, which is initialized by MyClass()
, then they will use the same reference.
Array(repeating: Array(repeating: MyClass(), count: 80), count: 24)
doesn't create a new instance of MyClass
in each array element. This method only creates MyClass
once and puts it into the array.
Here's a safe way to initialize a multidimensional array.
private var matrix: [[MyClass]] = MyClass.newMatrix()
private static func newMatrix() -> [[MyClass]] {
var matrix: [[MyClass]] = []
for i in 0...23 {
matrix.append( [] )
for _ in 0...79 {
matrix[i].append( MyClass() )
}
}
return matrix
}