我有一个值数组,例如a = [1,2,3]和字典数组b = [{{2:“ a”},{3:“ b”},{45:“ r”} ,{16:“ a”}]。我如何从b中获取与数组中的值匹配的键的值。有人可以给我提示吗?谢谢。
答案 0 :(得分:0)
在objective-c中
NSMutableArray *c = [[NSMutableArray alloc] init];
for (NSNumber *i in a) {
BOOL iFound = NO;
for (NSDictionary *dict in b) {
if ((NSNumber *)[[dict allKeys] firstObject] == i) {
iFound = YES;
[c addObject:(NSString *)[[dict allValues] firstObject]];
}
}
if (!iFound) {
[c addObject: [NSNull null]];
}
}
NSLog(@"%@",c);//("<null>",a,b)
迅速
let a = [1,2,3]
let b = [[2:"a"],[3:"b"],[45:"r"],[16:"a"]]
let c = a.map { i in b.first(where: { $0.keys.first == i })?.values.first }
print(c)//[nil, Optional("a"), Optional("b")]