【发布时间】: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