简体   繁体   中英

Combine large number of NSArrays into single NSArray in Objective-C or Swift

I can combine two NSArrays with the following code:

NSArray *combinedArray =firstArray?[firstArray arrayByAddingObjectsFromArray:secondArray]:[[NSArray alloc] initWithArray:secondArray];

If you have a large number of arrays such as ten or more, is there a simpler way to combine them than one by one?

If we are talking about Swift and all you need it's a short way, then you can do it like this:

let a = [0, 1]
let b = [2, 3]
let c = [4, 5]

let d = [a, b, c].flatMap { $0 }

LinqToObjectiveC may be your help.

This project contains a collection of NSArray and NSDictionary methods that allow you to execute queries using a fluent syntax, inspired by Linq.

I think you can merge ten or more arrays simply like below.

id mergedArray = [tenOrMoreArrays linq_aggregate:^id(id item, id aggregate) {
    return [aggregate arrayByAddingObjectsFromArray:item];
}];

*I have never tried this project, but I think it's worth to try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM