2
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 5 years have passed since last update.

Swiftでfor文の最後だけ処理をする

Last updated at Posted at 2020-03-14

for (i, message) in messages.enumerated() {
    // 全部にしたい処理
    if (i == messages.endIndex - 1) {
        // 最後だけしたい処理
    }
}

まずenumerated()を使うことでi(ここでindexでなく敢えてiを使ったのはenumerated()で取得できるのはただのカウントだから)を取得できるが、逆にendIndexは配列しか持っていない。

Swift3.0からfor文が使えなくなりfor-in文かforEach、もしくはmapなどしか使えなくなった。なので上記のenumurated()を使った「何回目の処理か」を取得する方法が散見されるが、これはindexでないというのが正しい説明のよう。

https://qiita.com/motokiee/items/4886b603631a7c076f46
https://qiita.com/a-beco/items/0fcfa69cca20a0ba601c

messages.countでも同じ値が帰ってくるはずだが、あれ、-1であってるんだっけ…。

guardを使わなかったのは、処理を抜ける時にbreakreturnの違いもあってこんがらがりそうだったから。breakは今の繰り返し処理を抜けて次の繰り返しを始めるが、returnを使っちゃうとfor-inの処理がそこですべて終了しちゃう。

2
2
1

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