Created
February 10, 2021 13:50
-
-
Save sbooth/ab9f5168b92e239077e361c9dd62392b to your computer and use it in GitHub Desktop.
Functional methods for NSArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Copyright (c) 2020 - 2021 Stephen F. Booth <[email protected]> | |
// MIT license | |
// | |
#import <Foundation/Foundation.h> | |
NS_ASSUME_NONNULL_BEGIN | |
@interface NSArray<ObjectType> (SFBFunctional) | |
/// Returns an array containing the results of applying \c block to each element in \c self | |
- (NSArray *)mappedArrayUsingBlock:(id (^)(ObjectType obj))block; | |
/// Returns a copy of \c self including only elements for which \c block returns \c YES | |
- (NSArray<ObjectType> *)filteredArrayUsingBlock:(BOOL (^)(ObjectType obj))block; | |
@end | |
NS_ASSUME_NONNULL_END |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Copyright (c) 2020 - 2021 Stephen F. Booth <[email protected]> | |
// MIT license | |
// | |
#import "NSArray+SFBFunctional.h" | |
@implementation NSArray (SFBFunctional) | |
- (NSArray *)mappedArrayUsingBlock:(id (^)(id))block | |
{ | |
NSParameterAssert(block != NULL); | |
NSMutableArray *result = [NSMutableArray arrayWithCapacity:self.count]; | |
for(id obj in self) { | |
id newobj = block(obj); | |
[result addObject:(newobj ?: [NSNull null])]; | |
} | |
return result; | |
} | |
- (NSArray *)filteredArrayUsingBlock:(BOOL (^)(id))block | |
{ | |
NSParameterAssert(block != NULL); | |
return [self objectsAtIndexes:[self indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { | |
#pragma unused(idx) | |
#pragma unused(stop) | |
return block(obj); | |
}]]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment