Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to addObject as NSMutableArray in NSMutableArray in swift

I want to addObject of NSMutableArray into NSMutableArray so how can I achieve this in swift. and also retrieve it so please help me because right now I'm learning swift.

Indirectly say that I want 2D array means NSMutableArray of NSMutableArray.

//The below 2 lines iterative!
var dict:NSMutableDictionary? = NSMutableDictionary();
 linePointsArray!.addObject(dict!);

// and below 2 line is execute after complete the above iteration
 arrLine!.addObject(linePointsArray!);
 linePointArray!.removeAllObject();

//after that the above whole process is done iterative.
like image 922
JAY RAPARKA Avatar asked Oct 09 '14 10:10

JAY RAPARKA


People also ask

What is NSMutableArray in Swift?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can we use NSArray in Swift?

In Swift, the NSArray class conforms to the ArrayLiteralConvertible protocol, which allows it to be initialized with array literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).


2 Answers

If I am not wrong you want to add an object of NSMutableArray in another NSMutableArray you can do it by following code

var myArray : NSMutableArray = ["Hello"]
var arrayOfArray : NSMutableArray = [myArray]

// Insert more arrays with insertObject or addObject

arrayOfArray.insertObject(myArray, atIndex: 0)
arrayOfArray.addObject(myArray)

//Retrive
var newArray:NSMutableArray = arrayOfArray[0] as NSMutableArray
println("\(newArray)")

For Swift 3:

var myArray : NSMutableArray = ["Hello"]
var arrayOfArray : NSMutableArray = [myArray]

// Insert more arrays with insertObject or addObject

arrayOfArray.insert(myArray, at: 0)
arrayOfArray.add(myArray)

//Retrive
var newArray:NSMutableArray = arrayOfArray[0] as! NSMutableArray
print("\(newArray)")
like image 56
Rein rPavi Avatar answered Sep 23 '22 06:09

Rein rPavi


Here is an example:

var mutableArray: NSMutableArray = []
var nestedMutableArray: NSMutableArray = []
mutableArray.addObject(nestedMutableArray)
var retrievedNestedMutableArray:NSMutableArray = mutableArray[0] as NSMutableArray
like image 44
Kirsteins Avatar answered Sep 20 '22 06:09

Kirsteins