Search code examples
objective-carraysswiftswift3nsarray

Converting between Swift and Objective C arrays


In my application I have some underlying legacy code written in Objective C, while the overlapping method is written in Swift.

Now the problem is that the Swift code uses Swift arrays [Int], but the Objective C methods require NSArray and NSMutableArray.

How to cast/convert between the different array types?

Swift code:

/* 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 method signatures (should not be modified):

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

Solution

  • Here is my solution:

    /* 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
    }