LoginSignup
4
5

More than 5 years have passed since last update.

NSArray内のオブジェクトを検索し、そのindexを取得する(indexOfObjectPassingTest)

Last updated at Posted at 2016-05-20

地道にfor文でループさせても良いのですけれども。SwiftからCスタイルfor文が無くなることですし、「今更for文を使うのはいかがなものか」と思い、他の方法を調べました。

NSArrayのメソッド indexOfObjectPassingTest を使用します。

// 例:Userクラスの配列から、userId == 123のユーザーのindexを得る
NSUInteger index = [userArray indexOfObjectPassingTest:^BOOL(id  _Nonnull obj,
                                                              NSUInteger idx,
                                                              BOOL * _Nonnull stop) {
    User* user = (User*)obj;
    return user.userId == 123;
}];

※条件がヒットしない場合は、NSNotFoundが返ってきます。

参考サイト

4
5
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
4
5