Contents

sample(type:predicate:)

Returns a sample predicate that matches samples.

Declaration

static func sample(type sampleType: HKSampleType, predicate: NSPredicate? = nil) -> HKSamplePredicate<HKSample>

Parameters

  • sampleType:

    A type that matches samples.

  • predicate:

    An optional predicate that further restricts the results that the query returns.

Discussion

Use this method to create an HKSamplePredicate instance that you can use to query for a heterogenous set of sample types.

let stepType = HKQuantityType(.stepCount)
// Normally, you'd create a quantity predicate for step counts.
let stepPredicate = HKSamplePredicate.sample(type: stepType)

let highHeartRateType = HKCategoryType(.highHeartRateEvent)
// Normally, you'd create a category predicate for high heart rate events.
let highHeartRatePredicate = HKSamplePredicate.sample(type: highHeartRateType)

// By using sample predicates, you can query for different sample types.
let descriptor = HKSampleQueryDescriptor(
    predicates: [stepPredicate, highHeartRatePredicate],
    sortDescriptors: [],
    limit: 10)

// However, the results are an array of HKSample objects.
// You'll need to downcast them to access the data.
let results = try await descriptor.result(for: store)

See Also

Creating Sample Predicates