How to cast a swift array of tuples to NSMutableArray?

只谈情不闲聊 提交于 2019-12-23 09:43:37

问题


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 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)


来源:https://stackoverflow.com/questions/36611440/how-to-cast-a-swift-array-of-tuples-to-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!