Fabrizio Bartolomucci
Fabrizio Bartolomucci

Reputation: 4948

Argument type '[HKCategoryType?]' does not conform to expected type 'Hashable'

I am trying to request the authorisation for a Category in healthkit by using code:

let healthKitStore: HKHealthStore = HKHealthStore()
let healthKitTypesToWrite = Set(arrayLiteral:[
    HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifierMindfulSession)
    ])
healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in

    if( completion != nil )
    {
      completion(success:success,error:error)
    }
}

from https://www.raywenderlich.com/86336/ios-8-healthkit-swift-getting-started.

Yet when I do so I get:

Argument type '[HKCategoryType?]' does not conform to expected type 'Hashable'

How do I save a category in Healthkit and is there in general a tutorial dedicated to HKCategoryType and also possibly HKCategoryTypeIdentifierMindfulSession?

Upvotes: 1

Views: 1400

Answers (1)

OOPer
OOPer

Reputation: 47876

The linked article is not a good example of creating a Set from ArrayLiteral.

You need to pass a Set<HKSampleType> to requestAuthorization(toShare:read:) (the method has been renamed in Swift 3), and Swift is not good at inferring collection types.

So, you'd better explicitly declare each type of healthKitTypesToWrite and healthKitTypesToRead.

let healthKitTypesToWrite: Set<HKSampleType> = [
    HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.mindfulSession)!
]
let healthKitTypesToRead: Set<HKObjectType> = [
    //...
]
healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) -> Void in

    completion?(success, error)
}

With giving an ArrayLiteral to some Set type, Swift tries to convert the ArrayLiteral to Set, internally calling Set.init(arrayLiteral:). You usually have no need to use Set.init(arrayLiteral:) directly.

Upvotes: 6

Related Questions