假设我有两个我事先不知道的东西,比如:

NSDictionary *dictA = @{ @"key1" : @1,
                         @"key2" : @2  };

NSDictionary *dictB = @{ @"key1" : @"a string" };

我想找到NSDictionaries的键和dictB的键或值之间的第一个匹配。dictA的每个键都是nsnumber或string。如果是一个数字,尝试从dictB的值中找到匹配项。如果是字符串,请尝试从dictA的键中查找匹配项。
使用for循环,它看起来像这样:
id match;
for (id key in dictA ) {
    for (id _key in dictB {
        if ( [_key is kindOfClass:NSNumber.class] && _key == dictA[key] ) {
            match = _key
            goto outer;
        }
        else if ( [_key is kindOfClass:NSString.class] && [_key isEqualToString:key] ) {
            match = _key
            goto outer;
        }
    }
};
outer:;

NSString *message = match ? @"A match was found" : @"No match was found";
NSLog(message);

我怎么能用reactivecococoa用dictARACSequence方法重写它,使它看起来像:
// shortened pseudo code:
// id match = [dictA.rac_sequence compare with dictB.rac_sequence using block and return first match];

最佳答案

您基本上想创建字典的笛卡尔积并在其上进行选择。据我所知,reactivecocoa中没有默认的运算符可以帮您实现这一点。(在linq中有用于此操作的运算符。)在rac中,最简单的解决方案是使用scanWithStart:combine:方法来实现此操作。一旦笛卡尔准备就绪,filter:take:1操作将产生您选择的序列。

NSDictionary *adic = @{@"aa":@"vb", @"ab": @"va"};
NSDictionary *bdic = @{@"ba": @"va", @"bb":@"vb"};;

RACSequence *aseq = adic.rac_keySequence;
RACSequence *bseq = bdic.rac_keySequence;

RACSequence *cartesian = [[aseq scanWithStart:nil combine:^id(id running, id next_a) {
    return [bseq scanWithStart:nil combine:^id(id running, id next_b) {
        return RACTuplePack(next_a, next_b);
    }];
}] flatten];

RACSequence *filteredCartesian = [cartesian filter:^BOOL(RACTuple *value) {
    RACTupleUnpack(NSString *key_a, NSString *key_b) = value;
    // business logic with keys
    return false;
}];

RACSequence *firstMatch = [filteredCartesian take:1];

10-06 01:17