Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift:配列に初期要素を複数セットする時の罠

Last updated at Posted at 2020-09-28

配列に初期要素を複数セットする方法はいくつかある。

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

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

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

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

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

// 他にもあるかも

ここで方法4に注目すると、repeatingに初期要素、countに要素数を渡すことでいい感じに初期化ができそうだが、他の3つの方法と違う点がある。

// 方法1で要素同士を比較してみる
print(array1[0] === array1[1]) // -> false
print(array1[1] === array1[2]) // -> false
// 結果は方法2,3も同様

// 方法4で要素同士を比較してみる
print(array4[0] === array4[1]) // -> true
print(array4[1] === array4[2]) // -> true

方法4では全て同じオブジェクトを指すことになっている。classのインスタンスをrepeatingに渡すと全く同じものを繰り返し配列に詰めてしまう。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?