我有一个ArraySlice<Dictionary<String, String>>
,里面只包含一个字典。如下所示:
[["high": "4", "investpercent": "6.0", "objective": "2.0", "savings": "2.0", "expenses": "1.0", "date": "2017-09-26", "low": "2"]]
但是我想用下标来操作字典,而这在ArraySlice中没有实现。根据在SO中发现的问题,在典型的片中,将执行以下操作:
let dictionary = ["a": 1, "b": 2, "c": 3]
var smallerDictionary: [String: Int] = [:]
for (key, value) in dictionary.dropFirst() {
smallerDictionary[key] = value
}
print(smallerDictionary) // ["a": 1, "c": 3]
我尝试过但在ArraySlice中不起作用。
答案 0 :(得分:1)
如果您的ArraySlice
被称为slice
,请使用slice.first!
或slice[slice.startIndex]
来访问包含的字典:
let slice: ArraySlice<[String:String]> = [["high": "4", "investpercent": "6.0", "objective": "2.0", "savings": "2.0", "expenses": "1.0", "date": "2017-09-26", "low": "2"]]
var smallerDictionary: [String: String] = [:]
for (key, value) in slice.first!.dropFirst() {
smallerDictionary[key] = value
}
print(smallerDictionary)
注意:在字典上调用dropFirst()
会给您带来意想不到的结果,因为字典是无序。
不用说,在尝试访问包含的词典之前,应确保ArraySlice
不为空。您可以通过显式检查slice.count > 0
,!slice.isEmpty
或正确展开slice.first
来做到这一点。