How to cast a swift array of tuples to NSMutableArray?


How to cast a swift array of tuples to NSMutableArray?

I have swift array of tuples [(String, String)] and would like to cast this array to NSMutableArray. I have tried this and it is not working: 
let myNSMUtableArray = swiftArrayOfTuples as! AnyObject as! NSMutableArray


Solution 1:

Since swift types like Tuple or Struct have no equivalent in Objective-C they can not be cast to or referenced as AnyObject which NSArray and NSMutableArray constrain their element types to.

The next best thing if you must return an NSMutableArray from a swift Array of tuples might be returning an Array of 2 element Arrays:

let itemsTuple = [("Pheonix Down", "Potion"), ("Elixer", "Turbo Ether")]
let itemsArray = { [$0.0, $0.1] }
let mutableItems = NSMutableArray(array: itemsArray)

Solution 2:

There are two problems with what you are trying to do:

  • Swift array can be cast to NSArray, but it cannot be cast to NSMutableArray without constructing a copy
  • Swift tuples have no Cocoa counterpart, so you cannot cast them or Swift collections containing them to Cocoa types.

Here is how you construct NSMutableArray from a Swift array of String objects:

var arr = ["a"]
let mutable = (arr as AnyObject as! NSArray).mutableCopy()