12
8

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 5 years have passed since last update.

Swift - init(repeating:count:)で配列を生成するときの注意点

Posted at

##基本的な使い方

// 4人で点数を競うときの初期値を0でいれておく

var playerScores = Array(repeating: 0, count: 4)
print(playerScores) // [0, 0, 0, 0]

// 書くプレイヤーがスコアを獲得
playerScores[0] += 5
playerScores[1] += 10
playerScores[2] += 15
playerScores[3] += 20
print(playerScores) // [5, 10, 15, 20]

##クラスのインスタンスを格納する配列を生成する

class Player {
  var name = ""
  var score = 0
}

var players = Array(repeating: Player(), count: 4)

// 書くプレイヤーに名前を代入
players[0].name = "John"
players[1].name = "Paul"
players[2].name = "George"
players[3].name = "Ringo"

players.forEach { player in
  print(player.name)
}

/*
Ringo
Ringo
Ringo
Ringo
みんなRingoになってしまった
*/

クラスのような参照型の場合、同じ参照を持つインスタンスがrepeatingにより複数生成されてしまいます。例えば、上記のようにクラスのインスタンスを配列で格納し、セルに表示する情報を管理する場合などは、1つの要素の情報を変えると他の要素にまで影響があるので注意が必要です。

##解決策

structなら値型なので上記のように1つの要素の値を変更すると、他の要素まで影響があるということはありません。

struct Player {
  var name = ""
  var score = 0
}

var players = Array(repeating: Player(), count: 4)

// 書くプレイヤーに名前を代入
players[0].name = "John"
players[1].name = "Paul"
players[2].name = "George"
players[3].name = "Ringo"

players.forEach { player in
  print(player.name)
}

/*
John
Paul
George
Ringo
*/
12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?