【问题标题】:Converting between Swift and Objective C arrays在 Swift 和 Objective C 数组之间转换
【发布时间】:2018-05-17 16:25:12
【问题描述】:

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

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

如何在不同的数组类型之间进行转换/转换?

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;

【问题讨论】:

  • 尝试投射(self.remainingOrders as!NSArray)。
  • self.remainingOrders = remainingOrders as NSArray as! [Int]; 适用于该行

标签: objective-c arrays swift swift3 nsarray


【解决方案1】:

这是我的解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    相关资源
    最近更新 更多