LoginSignup
32
36

More than 3 years have passed since last update.

Swift:配列で全てに同じ初期値を入れて初期化する方法

Last updated at Posted at 2017-06-23

背景

Swiftは配列が便利ですよね。けれどC言語のように簡単に初期値を格納した大きな配列を宣言できないと思っていました。いやぁ、できるんですね。

今までやっていた方法

var intArray = [Int]()
for _ in (0 ..< 100) {
    intArray.append(5)
}

一行で済む方法

var intArray = [Int](repeating: 5, count: 100) //[5, 5, 5,...,5]

var strArray = [String](repeating: "hello", count: 50) //["hello", "hello",...,"hello"]

repeating:とcount:を使えば同じ値を一気に繰り返し格納できるんですね。

注意点

Swift:配列に初期要素を複数セットする時の罠
こちらの記事にも書いてありますが、repeating:count:を使う場合、クラスインスタンスを初期値として使うと、全部同じ参照になってしまいます。つまり、配列のどれかのインスタンスをいじると、配列全体の要素にも変更が加わってしまいます。

32
36
2

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
32
36