Getting activity name through HKWorkoutActivityType in HealthKit
Issue #186
After fetching workouts with HKObjectType.workoutType() , we get HKWorkoutActivityType , which is an enum enum HKWorkoutActivityType : UInt . As of Swift 4.2, there are no way to get enum case as String because this enum has type UInt .
Though there will be some manual involved, we can build a generator to get all the enum case names. Here we will write code to generate code, and use that generated code to examine all the values.
Execute this Swift code in our iOS app
1 | func makeCode(string: String) { |
Where string is all the cases from HKWorkoutActivityType, for example
case archery
The constant for shooting archery.
case bowling
The constant for bowling
case fencing
The constant for fencing.
case gymnastics
Performing gymnastics.
case trackAndField
Participating in track and field events, including shot put, javelin, pole vaulting, and related sports.
What the code does is to use regular expression to examine all the names after case , and build our code
1 | dictionary[HKWorkoutActivityType.americanFootball.rawValue] = “americanFootball” |
The above generated code with dictionary contains rawValue as key and the enum case name as value .
Later when we get any HKWorkoutActivityType , we can compare with this dictionary to find the actual name. This is better than hardcode activity name with numbers because those rawValue are just implementation detail