Swift: A trap when setting multiple initial elements in an array

There are several ways to set multiple initial elements in an array.

class Hoge {
    var num: Int
    init(num: Int) {
        self.num = num
    }
}

//Method 1
var array1: [Hoge] = [
    Hoge(num: 0),
    Hoge(num: 0),
    Hoge(num: 0)
]

//Method 2
var array2 = [Hoge]()
for _ in (0 ..< 3) {
    array2.append(Hoge(num: 0))
}

//Method 3
var array3: [Hoge] = (0 ..< 3).map({ _ -> Hoge in
    return Hoge(num: 0)
})

//Method 4
var array4 = [Hoge](repeating:Hoge(num:0),count:3)

//There may be others

Focusing on method 4 here, it seems that it can be initialized nicely by passing the initial element to repeating and the number of elements to count, but there are differences from the other three methods.

//Compare the elements with method 1
print(array1[0] === array1[1]) // -> false
print(array1[1] === array1[2]) // -> false
//The result is method 2,Same for 3

//Compare the elements with method 4
print(array4[0] === array4[1]) // -> true
print(array4[1] === array4[2]) // -> true

Method 4 is supposed to point to the same object. If you pass an instance of class to repeating, you will repeatedly pack the exact same thing into an array.

Recommended Posts

Swift: A trap when setting multiple initial elements in an array
When seeking multiple in a Java array
Be careful when deleting multiple elements from an array etc. with a for statement
[Swift] How to get the number of elements in an array (super basic)
Multidimensional array in Swift
[Ruby] Searching for elements in an array using binary search
Multiplication in a Ruby array
What to do when an UnsupportedCharsetException occurs in a lightweight JRE
[Ruby] I want to put an array in a variable. I want to convert to an array
How to output the value when there is an array in the array
Cast an array of Strings to a List of Integers in Java
Make an FPS counter in Swift
Specify multiple sort conditions in Swift
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
[Swift] Summary of how to remove elements from an array (personal note)
I want to ForEach an array with a Lambda expression in Java
[Java] [For beginners] How to insert elements directly in a 2D array
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement