在 Swift 中埂蕊,map filter reduce 等高階函數(shù)的存在可以讓我們更快的處理數(shù)據(jù)往弓。
在OC中實(shí)現(xiàn)對應(yīng)方法:
- map:處理數(shù)組中的每個(gè)元素疏唾,并返回一個(gè)新的結(jié)果數(shù)組。
- (NSArray *)_map:(id(^)(id))handle {
if (!handle || !self) return self;
NSMutableArray *arr = NSMutableArray.array;
for (id obj in self) {
id new = handle(obj);
[arr addObject:new];
}
return arr.copy;
}
/** Usages: */
NSArray *languages = @[@"objctive-c", @"java", @"swift",@"javascript", @"php"];
languages = [languages _map:^id _Nonnull(NSString *obj) {
return [obj stringByAppendingString:@" !!"];
}];
NSLog(@"%@", languages);
/** Prints
(
"objctive-c !!",
"java !!",
"swift !!",
"javascript !!",
"php !!"
)
*/
- filter:按照規(guī)則返回過濾之后的數(shù)組
- (NSArray *)_filter:(BOOL(^)(id))handle {
if (!handle || !self) return self;
NSMutableArray *arr = NSMutableArray.array;
for (id obj in self) {
if (handle(obj)) {
[arr addObject:obj];
}
}
return arr.copy;
}
/** Usages: */
NSArray *numbers = @[@1,@2,@5,@11,@6,@0,@3];
NSArray *oddArr = [numbers _filter:^BOOL(NSNumber *obj) {
return (obj.intValue %2 != 0);
}];
NSLog(@"%@", oddArr);
/** Prints
(
1,
5,
11,
3
)
*/
- reduce:按照規(guī)則將組內(nèi)元素一一合并函似,返回最終結(jié)果
- (id)_reduce:(id(^)(id, id))handle initial:(id)initial {
if (!handle || !self || !initial) return self;
if (self.count <1) return initial;
id value = initial;
for (id obj in self) {
value = handle(value, obj);
}
return value;
}
/** Usages: */
NSArray *numbers = @[@3,@2,@10];
id result = [numbers _reduce:^id _Nonnull(NSNumber *obj1, NSNumber *obj2) {
return @(obj1.intValue * obj2.intValue);
} initial:@1];
NSLog(@"%@", result);
// Prints "60"
NSArray *words = @[@"hello", @"world", @"good", @"night"];
id result = [words _reduce:^id _Nonnull(NSString *obj1, NSString *obj2) {
return [NSString stringWithFormat:@"%@%@", obj1, obj2];
} initial:@""];
NSLog(@"%@", result);
// Prints "helloworldgoodnight"
- foreach:對每個(gè)元素做操作
- (void)_forEach:(void(^)(id))handle {
if (!handle || !self) return;
for (id obj in self) {
handle(obj);
}
}
/** Usages: */
[subviews _forEach:^(UIView *view) {
[view removeFromSuperview];
}];
可改進(jìn):函數(shù)式調(diào)用
難點(diǎn):獲取 block 簽名函數(shù)