问题
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:
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)
回答2:
There are two problems with what you are trying to do:
- Swift array can be cast to
NSArray
, but it cannot be cast toNSMutableArray
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)
来源:https://stackoverflow.com/questions/36611440/how-to-cast-a-swift-array-of-tuples-to-nsmutablearray