Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My block-based solution might look a bit overkill, but if you have several of this requirements, it could be helpful:</p> <p>create a Category on NSArray:</p> <pre><code>@interface NSArray (FunctionalTools) - (NSArray *)arrayByPerformingBlock:(id (^)(id element))performBlock; @end @implementation NSArray (FunctionalTools) - (NSArray *)arrayByPerformingBlock:(id (^)(id element))performBlock { NSMutableArray *array = [NSMutableArray array]; for (id element in self){ [array addObject:performBlock(element)]; } return array; } @end </code></pre> <p>and use it like this:</p> <pre><code>#import "NSArray+FunctionalTools.h" //.... self.youtubeVideos = [NSArray arrayWithObjects: @"http://example.com/index.php?number=1&amp;keyword=", @"http://example.com/index.php?number=2&amp;keyword=", nil]; self.youtubeVideos = [youtubeVideos arrayByPerformingBlock:^id(id element) { return [element stringByAppendingString:@"KeyWord"];}]; NSLog(@"%@", youtubeVideos); </code></pre> <p>or even </p> <pre><code>self.youtubeVideos = [[NSArray arrayWithObjects: @"http://example.com/index.php?number=1&amp;keyword=", @"http://example.com/index.php?number=2&amp;keyword=", nil] arrayByPerformingBlock:^id(id element) { return [element stringByAppendingString:@"KeyWord"];}]; </code></pre> <p><strong>Edit</strong><br> I incorporated this example into a <a href="https://github.com/vikingosegundo/arraytools" rel="nofollow">sample project</a> I wrote to teach myself block-based techniques to use functional-style programming with Objective-C. Coming from Python I always missed List Comprehension like </p> <pre><code>l = ['aa', 'ab','c','ad','dd'] l = [i+i for i in l if i.startswith('a')] </code></pre> <p>Block-based it looks like this:</p> <pre><code>NSArray *array = [NSArray arrayWithObjects:@"aa", @"ab",@"c",@"ad",@"dd", nil]; array = [array arrayByPerformingBlock:^id(id element) { return [element stringByAppendingString:element]; } ifElementPassesTest:^BOOL(id element) {return [element hasPrefix:@"a"];}]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload