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