gpt4 book ai didi

ios - 从字典数组映射到 Swift 中的数字数组

转载 作者:行者123 更新时间:2023-11-28 05:56:25 29 4
gpt4 key购买 nike

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

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

Type 'Any' has no subscript members

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

最佳答案

你可以试试这个

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

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

关于ios - 从字典数组映射到 Swift 中的数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51378562/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com