在 Swift 和 Objective C 数组之间转换

Converting between Swift and Objective C arrays

在我的应用程序中,我有一些底层遗留代码是用 Objective C 编写的,而重叠方法是用 Swift 编写的。

现在的问题是 Swift 代码使用 Swift 数组 [Int],但是 Objective C 方法需要 NSArrayNSMutableArray .

如何在不同的数组类型之间cast/convert?

Swift代码:

/* The remaining orders are finally stored as [Int] */
static var remainingOrders:[Int]! = [Int]()

/* Handles the orders loaded event */
@objc static func ordersLoaded(notification:Notification) {
    let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>
    let orders:NSArray = userInfo["orders"] as! NSArray // orders is of type NSArray
    let remainingOrders:NSMutableArray = orderUtils.filterRemainingOrders(fromOrders: orders.mutableCopy() as! NSMutableArray); // but it needs to be passed as NSMutableArray
    self.remainingOrders = remainingOrders as! [Int]; // the NSMutableArray needs to be stored as [Int]
    downloadService.download([Any](self.remainingOrders)); // then remaining orders need to be passed as NSArray
}

Objective C 方法签名(不应修改):

/* Filters orders that haven't been downloaded yet */   
- (NSMutableArray *)filterRemainingOrdersFromOrders:(NSMutableArray *)orders;
/* Downloads orders */    
- (void)download:(NSArray*)orders;

这是我的解决方案:

/* The remaining orders are finally stored as [Int] */
static var remainingOrders:[Int]! = [Int]()

/* Handles the orders loaded event */
@objc static func ordersLoaded(notification:Notification) {
    let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>
    let orders:NSArray = userInfo["orders"] as! NSArray // orders is of type NSArray
    let remainingOrders:NSMutableArray = orderUtils.filterRemainingOrders(fromOrders: orders.mutableCopy() as! NSMutableArray); // but it needs to be passed as NSMutableArray
    self.remainingOrders = remainingOrders as NSArray as! [Int]; // the NSMutableArray needs to be stored as [Int]
    downloadService.download(self.remainingOrders); // then remaining orders need to be passed as NSArray
}