Convert NSMutableArray to Swift Array (Array[Type])

Peter Wood in Swift
03 Sep 2014, 18:23

Hi there!

Here’s one more tiny but helpful tip from my Swift experience.

In my relatively big Swift project I have to use Foundation framework classes, which sometimes causes certain issues. Today I’ll tell you about one of those issues and the solution to it.

Suppose we have a variable of NSMutableArray type and we need to convert it into, say, Swift array with strings. Apparently the code should look like:

var nsArray = NSMutableArray()  ...  var swiftArray = nsArray as [String]  

However, the compiler won’t accept it:
‘String’ is not identical to ‘AnyObject’

To resolve this, write the code as:

var nsArray = NSMutableArray()  ...  var swiftArray = nsArray as AnyObject as [String]  

Voila! Now we can work with such arrays like with any ordinary Swift array.

The same issue occurs (and the same solution can be applied) when converting NS(Mutable)Dictionary into Swift dictionary.

See you.

Leave a Reply