With Swift 4.0, I am trying to do a down cast between the built-in HealhKit class HKWorkout to my own custom class. My class inherits from HKWorkout. HKWorkout inherits from HKSample. Down casting to HKWorkout from HKSample works. So then why can't I further cast this to my own class? I'd like to perform the cast without explicitly looping over an array of samples if possible. The reason for my custom class is to store addl properties and methods.
//This works. Note I am not explicitly looping over samples array.
//samples is an array of HKSample objects.
let workouts:[HKWorkout] = samples as! [HKWorkout]
//Does not work. FRWorkout is my class, inherits from HKWorkout.
let workouts:[FRWorkout] = samples as! [FRWorkout]
The end goal is to get an array of FRWorkout objects instead of HHWorkout objects.
Below is complete context:
class FRWorkout: HKWorkout {
var customProperty:UInt = 0
}
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate,
ascending: false)
let query = HKSampleQuery(sampleType: HKObjectType.workoutType(),
predicate: nil,
limit: 50,
sortDescriptors: [sortDescriptor]) { (query, samples, error) in
//Here I want FRWorkout objects instead of HKWorkout. I need to add addl info to the HKWorkout. How can this be achieved?
guard let workouts = samples as? [HKWorkout], error == nil else {
completion(nil, error)
return
}
}
HKSampleQuery
will return instances of HKWorkout
since you are specifying HKObjectType.workoutType()
as the sampleType
.
You cannot get HKSampleQuery
to return instances of FRWorkout
since the HealthKit framework doesn't know anything about your subclass.
Even though you have declared your class, FRWorkout
to be a subclass of HKWorkout
, you are not receiving instances of FRWorkout
from HKSampleQuery
so you cannot downcast the returned objects.
As @KaneChehire pointed out, subclassing HRWorkout isn't the right approach in any case.