3

I have two array

var arr1 = [NSArray]()
var arr2 = [String]()

And I want to convert NSArray into String Array I am using

arr2 = arr1 as! [String]

But it giving me error :-

'NSString' is not a subtype of 'NSArray'

Is there any other method to convert?

Aditya Raj Gupta
  • 51
  • 1
  • 2
  • 4

1 Answers1

19
var arr1 = [NSArray]() 

is a swift array of NSArray. You are using wrong syntax for NSArray

In order to convert NSArray to swift Array

Use the proper syntax:

var arr1 = NSArray(objects: "a","b","c")

var objCArray = NSMutableArray(array: arr1)

if let swiftArray = objCArray as NSArray as? [String] {

    // Use swiftArray here
    print(swiftArray)
}

It will print

["a", "b", "c"]

Another way

let swiftArray: [String] = objCArray.compactMap({ $0 as? String })

no forced casting required.

Patrick Jackson
  • 18,766
  • 22
  • 81
  • 141
Rajan Maheshwari
  • 14,465
  • 6
  • 64
  • 98