如何根据Swift3中的数组按日期/月/年计算平均值

时间:2017-07-12 14:27:23

标签: arrays dictionary swift3

我有一个字典数组。

字典就像["date":"2017-07-03T10:12:00", "amount":2.1]

修改

让我们说,我有以下数组。

let dic1 = ["date":"2017-07-03T10:12:00", "amount":2.0]
let dic2 = ["date":"2017-07-03T11:15:03", "amount":4.0]
let dic3 = ["date":"2017-07-03T17:05:04", "amount":1.0]
let dic4 = ["date":"2017-07-04T09:05:03", "amount":3.0]
let dic5 = ["date":"2017-07-04T12:01:22", "amount":5.0]
let dic6 = ["date":"2017-07-04T19:01:01", "amount":2.0]
let array = [dic1, dic2, dic3, dic4, dic5, dic6]

现在我正在尝试从Array计算以下结果。

"date":"2017-07-03", "average":3.5
"date":"2017-07-04", "average":5.0
"date":"2017-07", "average":2.82..
"date":"2017", "average":2.82..

我可以使用以下代码获得所有数据的平均值,但我现在已经被卡住了。

let average = array.flatMap({ $0["amount"] as? Double }).reduce(0, +) / Double(array.count)

2 个答案:

答案 0 :(得分:1)

建议使用包含日期格式化程序的自定义结构将ISO8601字符串转换为Date

struct Item {
    let date : Date
    let amount : Double

    static let dateFormatter : ISO8601DateFormatter = {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions = [.withFullDate, .withTime, .withColonSeparatorInTime]
        return formatter
    }()

    init(date: String, amount: Double) {
        self.date = Item.dateFormatter.date(from: date)!
        self.amount = amount
    }
}

填充数组

let items = [Item(date : "2017-07-03T10:12:00", amount :2.0),
             Item(date : "2017-07-03T11:15:03", amount :4.0),
             Item(date : "2017-07-03T17:05:04", amount :1.0),
             Item(date : "2017-07-04T09:05:03", amount :3.0),
             Item(date : "2017-07-04T12:01:22", amount :5.0),
             Item(date : "2017-07-04T19:01:01", amount :2.0)]

创建一个函数,将数组和特定日期组件作为参数

func average(of items: [Item], matching components: DateComponents) -> Double
{
    let filteredDates = items.filter { Calendar.current.date($0.date, matchesComponents: components) }
    return filteredDates.map{ $0.amount }.reduce(0.0, +) / Double(filteredDates.count)
}

现在按日期组件过滤项目并返回平均值

average(of: items, matching: DateComponents(year: 2017, month: 7, day: 3))
average(of: items, matching: DateComponents(year: 2017, month: 7, day: 4))
average(of: items, matching: DateComponents(year: 2017, month: 7))
average(of: items, matching: DateComponents(year: 2017))

答案 1 :(得分:0)

您应该过滤数组并计算过滤值的平均值。此示例适用于2017年,但您也可以对其他值应用相同的方法。

let filteredArray = array.filter { Calendar.current.component(.year, from: $0) == 2017 }
let average = (filteredArray.map { $0 as? Double ?? 0 }).reduce(0, +) / Double(filteredArray.count)