(スタック上で)より多くのメモリを必要とする再帰を使用した別の答えですが、再帰が好きな人にとっては読みやすいです:
- (NSArray *) flatten;
{
NSMutableArray *flattedArray = [NSMutableArray new];
for (id item in self) {
if ([[item class] isSubclassOfClass:[NSArray class]]) {
[flattedArray addObjectsFromArray:[item flatten]];
} else {
[flattedArray addObject:item];
}
}
return flattedArray;
}
そして、テストを拡張します:
+ (void) unitTests;
{
NSArray *flattenedArray;
NSArray *initialArray1 = @[@[@23, @354, @1, @[@7], @[@[@3]]], @[@[@890], @2, @[@[@6], @8]]];
NSArray *expectedArray1 = @[@23, @354, @1, @7, @3, @890, @2, @6, @8];
flattenedArray = [initialArray1 flatten];
SPASLogDetail(@"flattenedArray: %@", flattenedArray);
AssertIf(![flattenedArray isEqualToArray:expectedArray1], @"Arrays are not equal");
NSArray *initialArray2 = @[@[@23, @354, @1, [@[@7] mutableCopy], @[@[@3]]], @[[@[@890] mutableCopy], @2, @[@[@6], @8]]];
NSArray *expectedArray2 = expectedArray1;
flattenedArray = [initialArray2 flatten];
SPASLogDetail(@"flattenedArray: %@", flattenedArray);
AssertIf(![flattenedArray isEqualToArray:expectedArray2], @"Arrays are not equal");
}