9

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
1
  • 1
    you can't. change the tuple for a 2D array [[String]] and save it as [AnyObject] Commented Apr 14, 2016 at 0:05

2 Answers 2

19

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)
Sign up to request clarification or add additional context in comments.

1 Comment

NSMutableArray(array: itemsArray) this was the trick
4

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)

Comments

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.