鉴于:
@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的评论,我试图确定创建此类延期的目的可能是什么。分开:
-
该属性用于接受闭包参数并返回NSArray的闭包。
-
在实现中,我们根据readonly属性为这个闭包创建getter。
通常我们会用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