17

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.

3 Answers 3

37

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

6 Comments

my newArray returns with 0 count
in my newArray there is a collection of NSMutableDictionary but it returns count 0
means myArray has objects of dictionary, but newArray returns count 0
or else modify your question with the code so that we can play that in playground
now also i solve my problem with nil the array instead of remove all object (but why this happen that i don't know this code is propare work in objective c)
|
8

Here is an example:

var mutableArray: NSMutableArray = []
var nestedMutableArray: NSMutableArray = []
mutableArray.addObject(nestedMutableArray)
var retrievedNestedMutableArray:NSMutableArray = mutableArray[0] as NSMutableArray

Comments

0
var nameArray: NSMutableArray = ["Hello", "I", "am", "Smith"]
var arrayOfnameArray: NSMutableArray = [nameArray]

arrayOfArray.add(nameArray)

// Retrieve
var newArray:NSMutableArray = arrayOfnameArray[0] as! NSMutableArray
print("\(newArray)")

1 Comment

Code answers are generally not accepted without an explanation of what this code actually achieves. So you'll need to add a bit more explanation on how this code can help people can solve their problem.

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.