在swift中将每日日期中的相似月份对象求和

时间:2018-05-05 19:04:48

标签: swift

Guys我的数据库的结构是存储每日步骤数据。我需要将每日步骤总结为每月一次。这是我的要求如下

//Daily Data from DB
let dailyData = [["steps": 1000,
                  "date": 2018/04/28],
                 ["steps": 1000,
                  "date": 2018/04/29],
                 ["steps": 1000,
                  "date": 2018/04/30],
                 ["steps": 1000,
                  "date": 2018/04/01],
                 ["steps": 1000,
                  "date": 2018/05/02],
                 ["steps": 1000,
                  "date": 2018/05/03],
                 ["steps": 1000,
                  "date": 2018/05/04],
                 ["steps": 1000,
                  "date": 2018/05/05],
                 ["steps": 1000,
                  "date": 2018/06/06],
                 ["steps": 1000,
                  "date": 2018/06/07]]

//I need to sum daily data to monthly data as follows
let monthlyData = [["steps": 4000,
                    "month": April],
                   ["steps": 4000,
                    "month": May],
                   ["steps": 2000,
                    "month": June]]

请帮我逻辑一下。在每日数据中,我也有字符串和日期的日期类型。

1 个答案:

答案 0 :(得分:1)

X

其中,

    let dailyData: [[String: Any]] =
                    [["steps": 1000, "date": "2018/04/28"],
                     ["steps": 1000, "date": "2018/04/29"],
                     ["steps": 1000, "date": "2018/04/30"],
                     ["steps": 1000, "date": "2018/04/01"],
                     ["steps": 1000, "date": "2018/05/02"],
                     ["steps": 1000, "date": "2018/05/03"],
                     ["steps": 1000, "date": "2018/05/04"],
                     ["steps": 1000, "date": "2018/05/05"],
                     ["steps": 1000, "date": "2018/06/06"],
                     ["steps": 1000, "date": "2018/06/07"]]

    let groupedDict = Dictionary(grouping: dailyData, by: { ($0["date"] as! String).prefix(7) })
    let mappedDict = groupedDict.map { ["month": findMonth(str: String($0)), "steps": $1.map({ $0["steps"] ?? 0 }) ] }
    let result = mappedDict.map { ["month": $0["month"] ?? "", "steps": ($0["steps"] as! [Int]).reduce(0, { $0 + $1 }) ] }
    print(result)

结果是:

func findMonth(str: String) -> String {
    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "yyyy/MM"
    let date = dateformatter.date(from: str)!

    dateformatter.dateFormat = "MMMM"
    return dateformatter.string(from: date)
}