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?

5
  • arr1 is Array<NSArray> (swift array of NSArray) , not NSArray Commented Nov 17, 2016 at 4:34
  • how can I convert can you please suggest? Commented Nov 17, 2016 at 4:36
  • You should read about swift syntax first... Commented Nov 17, 2016 at 4:38
  • arr1 is an array of arrays, not an array of strings. As an example, if the first element of arr1 contains an NSArray of [1, 2] and the second element is ["abc", "def"]. What do you want the string representation of this to be? Commented Nov 17, 2016 at 4:40
  • Array(nsArray) converts NSArray to [Any] Commented Nov 19, 2019 at 0:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No need NSMutableArray, just if let ar = arr1 as? [String] { should be enough.

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.