Help us understand the problem. What is going on with this article?

Swiftで多次元配列を使う場合

More than 3 years have passed since last update.

Swiftで多次元配列を使う

Swiftで多次元配列を使う際に引っかかってのでメモ。(swift3.0)

宣言方法

正しい宣言

test.swift
var test = [[string]]()
test.append(["a"])
print(test)
// 出力結果
[["a"]]

誤った宣言

test.swift
var test:[[string]] = [[]]
test.append(["a"])
print(test)
// 出力結果 
[[], ["a"]]

誤った宣言の場合はbuildは通るが、初期化の時点で配列の先頭に空の配列が出来てしまうのでNG。

要素を追加する場合

test.swift
let data = "a"
test[0].append(data)
print(test)
// 出力結果
fatal error: Index out of range

添字を指定して要素を追加するとIndex out of rangeになる。どうやら存在しない配列に対して要素の代入を行おうとしているかららしい。調べてみると以下の方法で解決できた。

test.swift
let data = "a"
test.append([String]())
test[0].append(data)
print(test)
// 出力結果
[["a"]]

test.append([String]()) // この一文を追加
上記のように予め初期化した配列を格納することで要素を追加することが出来た。しかし、もっと良い方法があると思うので分かったら再度更新します。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした