0
2

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】for文内のif letを省略できるらしい

Posted at

はじめに

Twitterで流れてきたツイートでこんなことができるんだ。。。
と思ったことがあったので記録しておきます。

以前書いたこちらの記事と似ていますね

色々なリファクタ術があって面白いです。

ツイートの画像が全てなのですが、一応記録しておきます。

実装

データ
let characters: [String?] = [
    "アイアンマン",
    "キャプテン・アメリカ",
    nil,
    "スパイダーマン",
    nil,
    "ハルク"
]
実装パターン1
for character in characters {
    if let character {
        print(character)
    }
}
実装パターン2
for case let character? in characters {
    print(character)
}

おまけ

characters
    .compactMap { $0 }
    .map { print($0) }

おわり

いろんな実装方法があって面白いです

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?