从字典数组映射到 Swift 中的数字数组
Posted
技术标签:
【中文标题】从字典数组映射到 Swift 中的数字数组【英文标题】:Mapping from array of dictionaries to array of numbers in Swift 【发布时间】:2018-12-24 23:44:34 【问题描述】:这是一个函数,它应该将包含 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
【参考方案1】:
你可以试试这个
if let ordersWithKeyValuePairs = userInfo["orders"] as? [[String:Any]]
let result = ordersWithKeyValuePairs.compactMap$0["orderID"] as? Int
【讨论】:
【参考方案2】:这是有效的,将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
【讨论】:
以上是关于从字典数组映射到 Swift 中的数字数组的主要内容,如果未能解决你的问题,请参考以下文章
从 Json 数据中分组,其中包含 Swift 4 中的字典数组