NSSet+Lookin.m 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // NSSet+Lookin.m
  3. // Lookin
  4. //
  5. // Created by Li Kai on 2019/1/13.
  6. // https://lookin.work
  7. //
  8. #import "NSSet+Lookin.h"
  9. @implementation NSSet (Lookin)
  10. - (NSSet *)lookin_map:(id (^)(id obj))block {
  11. if (!block) {
  12. NSAssert(NO, @"");
  13. return nil;
  14. }
  15. NSMutableSet *newSet = [NSMutableSet setWithCapacity:self.count];
  16. [self enumerateObjectsUsingBlock:^(id _Nonnull obj, BOOL * _Nonnull stop) {
  17. id newObj = block(obj);
  18. if (newObj) {
  19. [newSet addObject:newObj];
  20. }
  21. }];
  22. return [newSet copy];
  23. }
  24. - (id)lookin_firstFiltered:(BOOL (^)(id obj))block {
  25. if (!block) {
  26. NSAssert(NO, @"");
  27. return nil;
  28. }
  29. __block id targetObj = nil;
  30. [self enumerateObjectsUsingBlock:^(id _Nonnull obj, BOOL * _Nonnull stop) {
  31. if (block(obj)) {
  32. targetObj = obj;
  33. *stop = YES;
  34. }
  35. }];
  36. return targetObj;
  37. }
  38. - (NSSet *)lookin_filter:(BOOL (^)(id obj))block {
  39. if (!block) {
  40. NSAssert(NO, @"");
  41. return nil;
  42. }
  43. NSMutableSet *mSet = [NSMutableSet set];
  44. [self enumerateObjectsUsingBlock:^(id _Nonnull obj, BOOL * _Nonnull stop) {
  45. if (block(obj)) {
  46. [mSet addObject:obj];
  47. }
  48. }];
  49. return [mSet copy];
  50. }
  51. - (BOOL)lookin_any:(BOOL (^)(id obj))block {
  52. if (!block) {
  53. NSAssert(NO, @"");
  54. return NO;
  55. }
  56. __block BOOL boolValue = NO;
  57. [self enumerateObjectsUsingBlock:^(id _Nonnull obj, BOOL * _Nonnull stop) {
  58. if (block(obj)) {
  59. boolValue = YES;
  60. *stop = YES;
  61. }
  62. }];
  63. return boolValue;
  64. }
  65. @end