HKHealthStore 类型的值没有类型 dateOfBirthWithError

Value of type HKHealthStore has no type dateOfBirthWithError

我正在尝试使用 HealthKit 读取数据,但在我 运行 这段代码时一直遇到同样的问题:

func readAge() -> ( age:Int?)
{
    var error:NSError?
    var age:Int?

    // 1. Request birthday and calculate age
    if let birthDay = healthKitStore.dateOfBirthWithError(&error)
    {
        let today = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let differenceComponents = NSCalendar.currentCalendar().components(.YearCalendarUnit, fromDate: birthDay, toDate: today, options: NSCalendarOptions(0) )
        age = differenceComponents.year
    }
    if error != nil {
        print("Error reading Birthday: \(error)")
    }

    return (age)
}

它给我错误:Value of type HKHealthStore has no type dateOfBirthWithError

我不知道为什么这行不通,因为我在其他地方看到了几乎完全相同的代码。

在 Swift 2.0 中,采用错误输出参数的方法的处理方式不同于 Swift 1.0 和 Objective-C。方法名称只是 dateOfBirth,它会抛出一个 NSError,您可以使用 try 语句处理它。

使用 Swift 2 你可以这样做:

func readAge() -> ( age:Int?)
{
   var error:NSError?
    var age:Int?

    do {
      let birthDay = try healthKitStore.dateOfBirth()
      let today = NSDate()
      let calendar = NSCalendar.currentCalendar()
      let differenceComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: birthDay, toDate: today, options: NSCalendarOptions(rawValue: 0))
      age = differenceComponents.year
    } catch let error as NSError {
      print(error.localizedDescription)
    }

    return (age)
}