【问题标题】:How to convert HKQuanity to Int in Swift 2.0如何在 Swift 2.0 中将 HKQuanity 转换为 Int
【发布时间】:2015-10-15 17:54:16
【问题描述】:

这一定很简单,但我想不通。我只需要将 HKQuanity 转换为 Int。

【问题讨论】:

  • 不,我拿了一个 HKQuantitySample 并把它变成一个 HKQuantity : sample[2].quantity

标签: swift swift2 healthkit


【解决方案1】:

如果您有一个HKQuantitySample 对象,那么您可以使用doubleValueForUnit 函数将quantity 属性转换为Int,如下所示:

let value = Int(sample.quantity.doubleValueForUnit(HKUnit.countUnit()))

其中sampleHKQuantitySample

请记住,当您像这样传递可选绑定时,您需要正确地转换样本:

readFullSample(anyValueYouPassHere) { samples in
     for sample in samples as [HKQuantitySample] {
         let value = Int(sample.quantity.doubleValueForUnit(HKUnit.countUnit()))
     }
}

希望对你有所帮助。

【讨论】:

  • 我明白了:2015-10-15 14:05:53.135 Export Health[79376:4267474] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“尝试转换不兼容的单位: m, count'..... libc++abi.dylib: 以 NSException 类型的未捕获异常终止
  • 请将您的完整查询放在获得HKQuantitySample 对象的位置
  • func readFullSample(sampleType:HKSampleType, completion: (([HKQuantitySample]) -> Void)) { let stepsSampleQuery = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: 100, sortDescriptors: nil) { (query, results, error) in if let results = results as? [HKQuantitySample] { completion(results) } } // 不要忘记执行查询! self.healthKitStore.executeQuery(stepsSampleQuery) }
  • 同样的错误 readFullSample(HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!) { (samples) -> 样本中的样本无效为 [HKQuantitySample] { let value = Int(sample.quantity.doubleValueForUnit(HKUnit. countUnit())) } }
  • 你能在 Github 上分享你的项目吗?
猜你喜欢
  • 2015-08-26
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 2015-09-04
相关资源
最近更新 更多