Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 800
VYT Avatar asked Apr 13 '16 23:04

VYT


2 Answers

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 = itemsTuple.map { [$0.0, $0.1] }
let mutableItems = NSMutableArray(array: itemsArray)
like image 191
Nirma Avatar answered Oct 07 '22 20:10

Nirma


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"]
arr.append("b")
let mutable = (arr as AnyObject as! NSArray).mutableCopy()
mutable.addObject("c")
print(mutable)
like image 32
Sergey Kalinichenko Avatar answered Oct 07 '22 22:10

Sergey Kalinichenko