Search code examples
iosswifthealthkit

HKQuantityTypeIdentifier initialize with string


I am trying to create HKObjectType like following however all values are nill. I get enum values by string so I need to create object to get authentication.

let c = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.init(rawValue: "bodyFatPercentage"))

let d = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: "BodyFatPercentage"))

let e = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: "bodyFatPercentage"))

Solution

  • The raw value is wrong, check this

    print(HKQuantityTypeIdentifier.bodyFatPercentage.rawValue)
    // HKQuantityTypeIdentifierBodyFatPercentage
    

    so you got to write

    let e = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: "HKQuantityTypeIdentifierBodyFatPercentage"))
    

    But why not

    let c = HKObjectType.quantityType(forIdentifier: .bodyFatPercentage)