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?

2

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

0
self.MutableID.insertContentsOf(idArray as [AnyObject], at: 0)

7 Comments

NSMutableArray has no member insertConsentsOf
When you use Swift you shouldn't use NSArray and NSMutableArray directly. Use var MutableID: [Int] instead.
You can't add objects from a [AnyObject] to a [Int].
@SlopTonio If you need to use NSMutableArray, your question should make that clear with more than just the tags.
@nhgrif No need to cast idArray to [AnyObject] then. Or just use var MutableID: [AnyObject] if really necessary.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.