2016-09-23 125 views
1

我試圖通過代碼來請求授權的範疇中healthkit:參數類型「[HKCategoryType?]」不符合預期型「哈希的」

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) 
    } 
} 

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

然而,當我這樣做,我得到:

參數類型「[?HKCategoryType]」不符合預期型 「哈希的」

如何保存在Healthkit類別通常有一個專用於HKCategoryType的教程,也可能有HKCategoryTypeIdentifierMindfulSession?

回答

5

鏈接的文章不是從ArrayLiteral創建Set的好例子。

你需要通過Set<HKSampleType>requestAuthorization(toShare:read:)(該方法已在Swift 3中重命名),並且Swift不擅長推斷集合類型。

因此,您最好明確聲明每種類型的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) 
} 

隨着給人一種ArrayLiteral一些Set類型,斯威夫特嘗試將ArrayLiteral轉換爲Set,在內部調用Set.init(arrayLiteral:)。您通常不需要直接使用Set.init(arrayLiteral:)

相關問題