Search code examples
swiftglkitmyo

GLKQuaternion in Swift


Trying to re-write Objective-C code written for the Myo I came across the GLKQuaternion class which is a union and doesn't seem to be supported in Swift (Using GLKMath from GLKit in Swift).

What I am looking for is a workaround to get this to work. Maybe a hybrid application with Math being done in ObjectiveC so I can access those properties. What are my options?


Solution

  • Ended up using a bridge file and creating a small wrapper layer to allow me access to the data I wanted from Swift. I called it a polyfill, similar to what we had on the web to enhance capabilities of old browsers.

    The code is available on github. Particularly this commit will be of interest as it shows what needs to be done.

    Polyfill.h

    @interface OrientationData: NSObject
      @property (nonatomic) TLMAngle *pitch;
      @property (nonatomic) TLMAngle *yaw;
      @property (nonatomic) TLMAngle *roll;
    @end
    
    @implementation OrientationData
    @end
    
    @interface GLKitPolyfill: NSObject
    + (OrientationData *) getOrientation:(TLMOrientationEvent *)orientationEvent;
    @end
    

    Polyfill.m

    + (OrientationData *) getOrientation:(TLMOrientationEvent *)orientationEvent {
      TLMEulerAngles *angles = [TLMEulerAngles anglesWithQuaternion:orientationEvent.quaternion];
    
      OrientationData *result = [OrientationData new];
      result.pitch = angles.pitch;
      result.yaw = angles.yaw;
      result.roll = angles.roll;
    
      return result;
    }
    

    ViewController.swift

    let angles = GLKitPolyfill.getOrientation(orientationEvent)
    let pitch = CGFloat(angles.pitch.radians)
    let yaw = CGFloat(angles.yaw.radians)
    let roll = CGFloat(angles.roll.radians)
    

    Apples Mix & Match guide gives good tips on how to make Obj-C work with Swift and vice-versa.