Jack.Right
Jack.Right

Reputation: 994

how to add two mutable array? Swift

In my app I want to implement pull down to refresh. So when scroll view scroll down its load more data. Now first time when page loads I save data in videoArray array, and when scroll down I got data in videoArray2 array so how can I add value of videoArray2 to videoArray? both are nsmuttablearray.

Here is my code:

var videoArray : NSMutableArray = NSMutableArray()
var videoArray2 : NSMutableArray = NSMutableArray()

First time I stored value in this array

self.videoArray = (response.result.value)?.valueForKey("posts") as! NSMutableArray

Second time I stored value in this array

self.videoArray2 = (response.result.value)?.valueForKey("posts") as! NSMutableArray

This is how I tried to append

for enumerator in self.videoArray2
{
    self.videoArray.addObject(enumerator)
}

but its throwing error like

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

So how can I solve this?

Upvotes: 0

Views: 4418

Answers (4)

Raj Aggrawal
Raj Aggrawal

Reputation: 761

Replace this line code 

self.videoArray = (response.result.value)?.valueForKey("posts") as! NSMutableArray

With 

let vidArray = response.result.value)?.valueForKey("posts") as! NSArray;
self.videoArray = vidArray.mutableCopy() as! NSMutableArray


First Line of code get the data from server as NSArray and later second line creates a mutable copy of that array.

Now Code below Run as expected.
for enumerator in self.videoArray2
{
    self.videoArray.addObject(enumerator)
}

Now you can add objects to the mutable copy of the videoArray.

Upvotes: 0

Amit Singh
Amit Singh

Reputation: 2698

It is as simple as this in Swift way

var array : [AnyObject] = [AnyObject]()
var array1 : [AnyObject] = [AnyObject]()
//Add array like this
array.appendContentsOf(array1)

OR like this as declared by you

var videoArray : NSMutableArray = NSMutableArray()
var videoArray2 : NSMutableArray = NSMutableArray()
//Add like this
videoArray.addObjectsFromArray(videoArray2 as [AnyObject])

OR

videoArray2.enumerateObjectsUsingBlock { (data, index, finished) in
        self.videoArray.addObject(data)
    }

Upvotes: 5

abhishekkharwar
abhishekkharwar

Reputation: 3529

// (response.result.value)?.valueForKey("posts") returning the NSArray so you have to take it in an array object then you can transfer all objects to your mutablearray

let array = (response.result.value)?.valueForKey("posts") as! NSMutableArray
self.videoArray = NSMutableArray(array:array)

// Added objects from videoArray2 to videoArray

self.videoArray.addObjectsFromArray(self.videoArray2)

Upvotes: 2

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

let videoArray = (response.result.value)?.valueForKey("posts") as! NSArray
self.videoArray = NSMutableArray(array:videoArray)

and the same for the second array

Upvotes: 4

Related Questions