1
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 1 year has passed since last update.

オプショナルな配列に要素を追加する様々な方法(Swift)

Last updated at Posted at 2023-08-13

はじめに

components.queryItems[URLQueryItem]? 型の配列です。

var queryItems: [URLQueryItem]? { get set }

配列の要素は非オプショナル型ですが、配列自体がオプショナル型です。
このような配列に要素を追加する方法を紹介します。

環境

  • OS:macOS Ventura 13.4.1
  • Swift:5.8

オプショナルな配列に要素を追加する様々な方法

オプショナルな配列に要素を追加する様々な方法を紹介します。

前提として、配列が nil でない場合は先頭に元の要素を残すようにします。

デフォルト値を使って先頭に元の要素を残す

自分が考え得る中で最も短いコードです。

components.queryItems = (components.queryItems ?? []) + [
    .init(name: "zipcode", value: zipCode),
]

もう少しスマートに書ける気がしますが、今のところ一番好みです。

配列を一時変数に格納する

配列を一時変数に格納してアンラップし、構築して変数ごと代入します。

var queryItems = components.queryItems ?? []
queryItems += [
    .init(name: "zipcode", value: zipCode),
]
components.queryItems = queryItems

最初の方法より少し長いですが、こちらのほうがわかりやすいという人も多いと思います。

Xcodeのように型推論された型がinlay hintで表示されない場合、配列の型を明記するとわかりやすいです。

var queryItems: [URLQueryItem] = components.queryItems ?? []
queryItems += [
    .init(name: "zipcode", value: zipCode),
]
components.queryItems = queryItems

関数を使う

配列を2次元にしてすべての要素を突っ込み、最後に flatMap() で1次元にします。

components.queryItems = [
    (components.queryItems ?? []),
    [
        .init(name: "zipcode", value: zipCode),
    ],
]
    .flatMap { $0 }

上記だと最初の方法の下位互換っぽいので、 オプショナルな配列を compactMap() で潰すとより関数型チックに書けます。

components.queryItems = [
    components.queryItems,
    [
        .init(name: "zipcode", value: zipCode),
    ],
]
    .compactMap { $0 }
    .flatMap { $0 }

関数型プログラミングが好きな人にはよさそうです。

おわりに

オプショナルな配列に要素を追加する方法はたくさんあることがわかりました。
ほかにもありましたら、コメントなどで教えていただけると嬉しいです :relaxed:

参考リンク

1
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
1
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?