How to derive a value from a infinite number in Sw

2019-08-26 21:11发布

问题:

My function below will occasionally produce an infinite number. I had thought that I could use my rounding function below to avoid using the infinite number...in other words 1.333333333333(INF) rounded to 1.33, however the compiler still treats the result of the INF.rounded as infinite, how can I round so that I can still put out a value here? Speficially I'm trying to encode to JSON and getting this error:

metadata ERROR = invalidValue(inf, Swift.EncodingError.Context(codingPath: [Watch_Extension.HockeyTrackerMetadata.(CodingKeys in _B2A7010AF20490DAF638D1E0A01E4982).maximumCapableSpeed], debugDescription: "Unable to encode Double.infinity directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded.", underlyingError: nil))

//Calculation  
 func calculateMaximumAndAverageSkatingEfficiency() {

        let heartRateUnit:HKUnit = HKUnit(from: "count/min")
        let heartRatesAsDouble = heartRateValues.map { $0.quantity.doubleValue(for: heartRateUnit)}
        let maxHeartRate = heartRatesAsDouble.max()
        guard let maxHeartRateUnwrapped = maxHeartRate else { return }

        maximumEfficiencyFactor = ((1760.0 * (maxSpeed / 60)) / maxHeartRateUnwrapped).round(to: 2)

        guard let averageIceTimeHeartRateUnwrapped = averageIceTimeHeartRate else { return }

        averageEfficiencyFactor = ((1760.0 * (averageSpeed / 60)) / averageIceTimeHeartRateUnwrapped).round(to: 2)

    }

//Round extension I am using
extension Double {

    func round(to places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return Darwin.round(self * divisor) / divisor
    }

}

//Usage 
  if let averageEfficiencyFactorUnwrapped = averageEfficiencyFactor {
            metadata.averageEfficiencyFactor = averageEfficiencyFactorUnwrapped.round(to: 2)
        }

回答1:

"Infinite value" means that the value is positive or negative infinity, probably because it was the result of a division by zero or a similar mathematical operation. It does not mean that the value is a non-terminating decimal.

Make sure that maxHeartRateUnwrapped and averageIceTimeHeartRateUnwrapped are not zero.