我正在尝试重构以下代码:
var indices = [String:[Int:Double]]()
apps.forEach { app in indices[app] = [Int:Double]()}
var index = 0
timeSeries.forEach { entry in
entry.apps.forEach{ (arg: (key: String, value: Double)) in
let (app, value) = arg
indices[app]?[index] = value
}
index += 1
}
我有这样的签名:
var parameters = timeSeries.map{ entry in entry.apps as [String:Any] }
var indices = getIndices(with: apps, in: parameters) as? [String:[Int:Double]] ?? [String:[Int:Double]]()
而这个方法:
func getIndices(with source: [String], in entryParameters: [[String:Any]]) -> [String:[Int:Any]] {
var indices = [String:[Int:Any]]()
source.forEach { item in indices[item] = [Int:Any]() }
var index = 0
entryParameters.forEach { (arg: (key: String, value: Any)) in
let (key, value) = arg
indices[key]?[index] = value
index += 1
}
return indices
}
但是这样做(只在方法中,原始内容没有问题)会出现:entryParameters行显示'(key: String, value: Any)'不可转换为'[String : Any]'
我必须使用Any
的原因是另一个来源是[String:[Int:Bool]]
编辑:更多细节:
timeSeries是[TimeSeriesEntry]
// this will need to be defined per-model, so in a different file in final project
struct TimeSeriesEntry: Codable, Equatable {
let id: String
let uid: String
let date: Date
let apps: [String:Double]
let locations: [String:Bool]
func changeApp(app: String, value: Double) -> TimeSeriesEntry {
var apps = self.apps
apps[app] = value
return TimeSeriesEntry(id: self.id, uid: self.uid, date: self.date, apps: apps, locations: self.locations)
}
}
注释:
更改了调用签名,感谢impression。问题仍然存在。
[String:Any]
而不是[[String:Any]]
吧? - impression7vxtimeSeries.map
处出现Cannot convert value of type '[[String : Double]]' to expected argument type '[String : Any]'
错误-- 我添加了timeSeries结构的详细信息以增加清晰度。 - roberto tomástimeSeries.map{ entry in entry.apps }) as? [String:[Int:Double]] ?? [String:[Int:Double]]()
。所以,我猜这取决于你想要什么。在两种情况下,似乎都需要将其类型转换为[String:[Int:Double]]
或[String:[Int:Double]]()
。现在,你说你也需要它用于bool
。然而,如果是这样的话,当你将其带入参数时,你需要将你的[String:[Int:Double]]
转换为[String:Any]
,当它作为参数进入函数时。 - impression7vxtimeSeries.map{ entry in entry.apps }) as? [String:Any] ?? [String:[Int:Double]]()
,因为如果[String:Any]
返回nil,那么你就知道需要一个新的,即[String:[Int:Double]]
。 - impression7vx[String:Double]
的数组。强制转换是[String:[Int:Double]]
,同样是在返回值上进行的(我想赋值中左侧的类型说明不需要,但右侧需要)。[String:Double]
应该能够优雅地向下转换为[String:Any]
,而不需要强制转换,对吗? - roberto tomás