How would I combine two arrays in Objective-C?

后端 未结 3 1342
自闭症患者
自闭症患者 2021-01-31 01:00

What is the Objective-C equivalent of the JavaScript concat() function?

Assuming that both objects are arrays, how would you combine them?

相关标签:
3条回答
  • 2021-01-31 01:45

    NSArray's arrayByAddingObjectsFromArray: is more-or-less equivalent to JavaScript's .concat() method:

    NSArray *newArray=[firstArray arrayByAddingObjectsFromArray:secondArray];
    

    Note: If firstArray is nil, newArray will be nil. This can be fixed by using the following:

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

    If you want to strip-out duplicates:

    NSArray *uniqueEntries = (NSArray *)[[NSSet setWithArray:newArray] allObjects];
    
    0 讨论(0)
  • 2021-01-31 01:57

    Here's a symmetric & simple way by just beginning with an empty array:

    NSArray* newArray = @[];
    newArray = [newArray arrayByAddingObjectsFromArray:firstArray];
    newArray = [newArray arrayByAddingObjectsFromArray:secondArray];
    
    0 讨论(0)
  • 2021-01-31 01:58

    For Swift version its like charm :

    let a = [1,2,3]
    let b = [3,4]
    let c = a + b
    print(c)
    
    0 讨论(0)
提交回复
热议问题