-1

I have two arrays. One is:

var array = [[String]]()

The second one is:

var finalArray = NSMutableArray()

array is blank.

I want to copy all the data from the final array to array. For these two different types of array, direct this code won't work.

array = finalArray
Nikunj Kumbhani
  • 3,758
  • 2
  • 26
  • 51
  • 1
    Don't use `NSArray` or `NSMutableArray` in Swift. – rmaddy Nov 01 '19 at 04:38
  • You can't directly assign different types array to like this here your first array is **[[String]]** type so you need to convert finalArray elements to that type and then you can assign or add elements in that array – Nikunj Kumbhani Nov 01 '19 at 04:39
  • see this for [help1](https://stackoverflow.com/questions/27812433/how-do-i-make-a-exact-duplicate-copy-of-an-array) and [help2](https://www.freecodecamp.org/news/deep-copy-vs-shallow-copy-and-how-you-can-use-them-in-swift-c623833f5ad3/) – Anbu.Karthik Nov 01 '19 at 04:40
  • I guess in your actual question, you have stated that the data type of your array is [String]. But after edit, it is now looks like [[String]] in the question. It seems like a typo in the edit. – Subramanian Mariappan Nov 01 '19 at 04:50

1 Answers1

1

An NSArray can be converted to a Swift array of a given element type with the as? operator, like so:

array = finalArray as? [[String]] ?? []

Note that we have to use the conditional typecast operator as? because it's not known at compile-time whether finalArray actually is an array of string arrays (since NSArray does not use generics in Swift).

TylerP
  • 9,600
  • 4
  • 39
  • 43