【问题标题】:Mapping from array of dictionaries to array of numbers in Swift从字典数组映射到 Swift 中的数字数组
【发布时间】:2023-03-29 19:06:01
【问题描述】:

这是一个函数,它应该将包含 Dictionary<String, Any> 的订单 NSArray 的键值对数组转换为每个订单的 ID 数组 ([NSNumber])。

但是,我仍然遇到类型转换的问题,错误:

类型 'Any' 没有下标成员

如何在 Swift 中干净利落地执行映射?

@objc static func ordersLoaded(notification:Notification) -> [NSNumber] {   

    // Function receives a Notification object from Objective C     
    let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>

    // orders is an array of key-value pairs for each order Dictionary<String,Any>
    let ordersWithKeyValuePairs:NSArray = userInfo["orders"] as! NSArray // Here a typed array of Dictionaries would be preferred

    // it needs to be simplified to an array of IDs for each order (NSNumber)
    // orderID is one of the keys
    let orderIDs:[NSNumber];
    orderIDs = ordersWithKeyValuePairs.flatMap({$0["orderID"] as? NSNumber}) // Line with the error
    /*
    orderIDs = ordersWithKeyValuePairs.map({
        (key,value) in
        if key==["orderID"] {
            return value
        } else {
            return nil
        }
    }) as! [NSNumber]
    */

    return orderIDs
}

【问题讨论】:

  • NSArray 的定义类似于[Any],这就是您遇到问题的原因。不要在 Swift 中使用 NS 类,除非你真的必须这样做。在这种情况下,转换为预期的类型,可能是:[AnyHashable: Any]
  • 在执行orderIDs = ordersWithKeyValuePairs.flatMap({$0["orderID"] as? NSNumber})时仍然收到错误Type 'AnyHashable' has no subscript members

标签: ios swift mapping nsarray swift4


【解决方案1】:

你可以试试这个

if let ordersWithKeyValuePairs = userInfo["orders"] as? [[String:Any]] {

   let result = ordersWithKeyValuePairs.compactMap{$0["orderID"] as? Int }
}

【讨论】:

    【解决方案2】:

    这是有效的,将ordersWithKeyValuePairs 转换为[Dictionary&lt;String, Any&gt;] 解决了我的问题:

    @objc static func ordersLoaded(notification:Notification) -> [NSNumber] {   
    
        // Function receives a Notification object from Objective C     
        let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>
    
        // orders is an array of key-value pairs for each order Dictionary<String,Any>
        let ordersWithKeyValuePairs:[Dictionary<String, Any>] = userInfo["orders"] as! [Dictionary<String, Any>]
        // it needs to be simplified to an array of IDs for each order (NSNumber)
        // orderID is one of the keys
        let orderIDs:[NSNumber];
        orderIDs = ordersWithKeyValuePairs.flatMap({$0["orderID"] as? NSNumber}) // Line with the error
    
        return orderIDs
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-22
      • 1970-01-01
      • 2015-10-17
      • 2019-07-30
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 2023-01-01
      • 1970-01-01
      相关资源
      最近更新 更多