在Swift中从字典数组到数字数组的映射

时间:2018-07-17 10:03:26

标签: ios swift mapping nsarray swift4

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

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

  

“任意”类型没有下标成员

如何在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
}

2 个答案:

答案 0 :(得分:1)

您可以尝试

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

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

答案 1 :(得分:0)

这是有效的方法,将ordersWithKeyValuePairs强制转换为[Dictionary<String, Any>]可以解决我的问题:

@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
}