参数类型'[HKCategoryType?]'不符合预期类型'Hashable'

Fab*_*cci 1 ios healthkit swift3

我试图通过使用代码请求对healthkit中的类别进行授权:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

然而,当我这样做时,我得到:

参数类型'[HKCategoryType?]'不符合预期类型'Hashable'

如何在Healthkit中保存类别,并且通常是一个专门用于HKCategoryType的教程,也可能是HKCategoryTypeIdentifierMindfulSession?

OOP*_*Per 6

链接的文章不是从ArrayLiteral创建Set的好例子.

你需要传递Set<HKSampleType>requestAuthorization(toShare:read:)(该方法已在斯威夫特3被重命名),而斯威夫特是不擅长推断集合类型.

所以,你最好明确声明每种类型的healthKitTypesToWritehealthKitTypesToRead.

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)
}
Run Code Online (Sandbox Code Playgroud)

通过将ArrayLiteral赋予某种Set类型,Swift尝试将ArrayLiteral转换为Set内部调用Set.init(arrayLiteral:).您通常无需Set.init(arrayLiteral:)直接使用.