0

I'm having trouble adding an existing array to the beginning of another array. For example: MutableID array contains 1,2,3,4,5 & idArray array contains 6,7,8

self.MutableID.addObjectsFromArray(idArray as [AnyObject])
//currently puts values to the end of the array not the beginning

this code outputs 1,2,3,4,5,6,7,8 but I want it to output 6,7,8,1,2,3,4,5

I need the values added to the beginning of self.MutableID Any suggestions on how I can accomplish this?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
SlopTonio
  • 1,105
  • 1
  • 16
  • 39

3 Answers3

0
self.MutableID.insertContentsOf(idArray as [AnyObject], at: 0)
fluidsonic
  • 4,655
  • 2
  • 24
  • 34
0

This question is the Swift version of this question which solves the problem in Objective-C.

If we must, for whatever reason, be using Objective-C's NSArray or NSMutableArray, then we can simply use a Swift translation of the code in my answer over there:

let range = NSMakeRange(0, newArray.count)
let indexes = NSIndexSet(indexesInRange: range)
oldArray.insertObjects(newArray as [AnyObject], atIndexes: indexes)

Where oldArray is an NSMutableArray and newArray is NSArray or NSMutableArray.

Or the other approach, append and reassign:

oldArray = newArray.arrayByAddingObjectsFromArray(oldArray as [AnyObject])

But the most correct thing to do would be to use the Swift Array type, and then use the insertContentsOf(_: Array, at: Int) method, as fluidsonic's answer describes.

Community
  • 1
  • 1
nhgrif
  • 61,578
  • 25
  • 134
  • 173
0

NSMutableArray has insertObjects method.

self.MutableID.insertObjects(otherArray as [AnyObject], atIndexes: NSIndexSet(indexesInRange: NSMakeRange(0, otherArray.count)))

Or you can assign the mutable array to a swift array and use insertContentsOf method ;)

self.MutableID = NSMutableArray(array: [1,2,3,4])
var otherArray = NSMutableArray(array: [6,7,8,9])

var swiftArr : [AnyObject] = self.MutableID as [AnyObject]
swiftArr.insertContentsOf(otherArray as [AnyObject], at: 0)
Mihriban Minaz
  • 3,043
  • 2
  • 32
  • 52