我有一个心率阵列。我想要的只是平均最后5分钟的心率。 (数组包含超过最后一小时的心率)。
class HeartRate
{
var hr = 0
var date : Date?
}
var arrHeartRate = [HeartRate]()
let minDate = Date().addingTimeInterval(-300) //get 5min before time
var avgHR = self.arrHeartRate.filter { (Item) -> Bool in
return Item.date! > minDate
}.reduce(0) { (res, item) -> Result<Any, <#Error: Error#>> in
return res
}
答案 0 :(得分:4)
以下是一些代码,它是不同stackoverflow答案的聚合。
class HeartRate
{
var hr = 0
var date: Date?
}
extension Collection where Iterator.Element == HeartRate, Index == Int {
/// Returns the average of all elements in the array
var average: Double {
return isEmpty ? 0 : Double(reduce(0) { $0 + $1.hr }) / Double(endIndex-startIndex)
}
}
var arrHeartRate = [HeartRate(), HeartRate()]
let minDate = Date().addingTimeInterval(-300) //get 5min before time
let rateInLast5Min = arrHeartRate.filter {
guard let date = $0.date else { return false }
return date > minDate
}
var avgHR = rateInLast5Min.average
答案 1 :(得分:3)
您可以分两步进行过滤和缩小。首先,在时间范围内获得一组心率
<?php
/**
* Webkul Software.
*
* @category Webkul
* @package Webkul_Marketplace
* @author Webkul
* @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
* @license https://store.webkul.com/license.html
*/
namespace Webkul\Marketplace\Controller\Account;
use Magento\Framework\App\Action\Action;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\App\RequestInterface;
/**
* Webkul Marketplace Account SaveAreaInfo Controller.
*/
class Saveareainfo extends Action
{
public function __construct()
{
parent::__construct();
}
public function execute()
{
die( " Hello Test .. " );
}
}
或者进行一些调整以从过滤后的数组中排除零日期
let filtered = arrHeartRate.filter{$0.date ?? Date() > minDate}
然后计算平均值并返回
let filtered = arrHeartRate.filter{$0.date ?? Date().addingTimeInterval(-500) > minDate}
答案 2 :(得分:1)
我没有运行它,但有一些调整应该是你正在寻找的
let rateInLast5Min = arrHeartRate.filter({ 0$.date! > minDate })
let hours = rateInLast5Min.map{ return $0.hr }.reduce(0, +)
let average = Double(hours)/Double(rateInLast5Min.count)