给出:
@interface NSArray (Sample)
@property (nonnull, nonatomic, readonly) NSArray *_Nonnull (^mapped)(id __nullable (^block)(id __nonnull));
@end
如何实现这一类别?我对这种块属性语法感到困惑。 这说明了类型注释:https://developer.apple.com/swift/blog/?id=25
这是我开始实施的目的:
@implementation NSArray (Sample)
typedef id __nullable (^block)(id __nonnull);
...
@end
后来尝试了这个:
@implementation NSArray (Sample)
typedef NSArray *_Nonnull (^mapped)( id __nullable (^block)(id __nonnull) );
-(mapped)mapped {
return ^( id __nullable (^block)(id __nonnull) ){
return @[@"what", @"the", @"heck"];
};
}
@end
稍后:
从技术上讲,我认为上述内容可以满足扩展程序的合同要求,但是根据bbum的评论,我试图确定创建此类扩展程序的意图。分开:
通常,我们将使用setter注入/设置该块,但是为了履行合同,我们可以将其构造为实例变量“ someMapped”,如下所示。
@implementation NSArray (Sample)
typedef NSArray *_Nonnull (^mapped)( id __nullable (^block)(id __nonnull) );
-(mapped)mapped {
//Normally someMapped block definition would be injected/set by the setter -(void) setMapped:(mapped) aMapped {
mapped someMapped = ^(id __nonnull someId) {
NSMutableArray * new = [[NSMutableArray alloc] init];
for( NSMutableDictionary* dict in self) {
NSMutableString * str = [dict objectForKey:someId];
[str stringByAppendingString:@".png"];
[new addObject:str];
}
return [new copy];
};
return someMapped;
}
@end
答案 0 :(得分:0)
不清楚您要做什么。您是否要在map
上实现NSArray
类型的函数?如果是这样,则不需要@property
,这意味着您正在存储与它们的实例关联的内容。您可能只需要一种方法:
typedef id __nullable (^bt_MapBlockT)(id __nonnull);
- (NSArray *)bt_map:(bt_MapBlockT) block;
// written in browser... probably hosed the syntax slightly.
有大量的示例关于如何在NSArray,btw上实现map-reduce-filter-Whatever。