LoginSignup
1
0

More than 5 years have passed since last update.

Swift で optional なアイテムを array に連結

Posted at

記事というより自分へのメモ

Array に Optional な Item を追加した時があった場合に、Item は値を持っているかもしれないし、nil かもしれません。仕方ないので、optional binding を使って連結していましたが、やっぱりなんかしっくりこないなと思っていました。

let item: String? = "a" // or nil
let items: [String] = ["b", "c", "d"]

var collection = [String]()
if let item = item {
    collection.append(item)
}
collection += items // ["a", "b", "c", "d"]

こんな書き方ができる事を見つけたので記録として残します。

let item: String? = "a"
let items: [String] = ["b", "c", "d"]

var collection = [item].flatMap { $0 } + items // ["a", "b", "c", "d"]

[執筆時点での環境に関する表記]

Xcode Version 8.2.1 (8C1002)
Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
1
0
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
0