我有 [Int64:[String:String]]
其中 Int64 是时间戳。如何检测和删除 [String:String]
中的参数之一是 ["name"] = "test"
并重复多次的同一天日期在字典中添加 ["times"]
的重复次数。
Ví dụ [Int64:[String:String]]
[1543058992:["name:"test"], 1543058988:["name:"test"],
1543058990:["name:"test"], 1543058984:["name:"test2"],
1543945308:["name:"test2"], 1543945208:["name:"test2]",
1550058984:["name:"test3"]]
hy vọng [Int64:[String:String]]
处理后:
[1543058992: ["name:"test", "times":"3"],
1543058993: ["name:"test2", "times":"1"],
1543945308: ["name:"test2", "times":"2"],
1550058984: ["name:"test3"]]
import Foundation
typealias YourDict = [Int64: [String: String]]
let initial: YourDict = [
1543058992: ["name": "test"],
1543058988: ["name": "test"],
1543058990: ["name": "test"],
1543058984: ["name": "test"],
1543945308: ["name": "test2"],
1543945208: ["name": "test2"],
1550058984: ["name": "test3"]
]
var result: YourDict = [:]
let calendar = Calendar.current
initial.forEach { item in
let key = item.key
let currentValueDict = item.value
var foundCheckingKey: Int64?
let date = Date(timeIntervalSince1970: TimeInterval(key * 1000))
if result.contains(where: { checkingItem in
let checkingKey = checkingItem.key
foundCheckingKey = checkingKey
let checkingDate = Date(timeIntervalSince1970: TimeInterval(checkingKey * 1000))
return calendar.isDate(date, inSameDayAs: checkingDate)
}) {
let previousCount = Int(result[foundCheckingKey!]!["times"]!)!
result[foundCheckingKey!]!["times"] = "\(previousCount + 1)"
} khác {
result[key] = ["name": currentValueDict["name"]!, "times": "1"]
}
}
print(result)
Tôi là một lập trình viên xuất sắc, rất giỏi!