objective-cextension-methodsobjective-c-category

Extension of a struct in Objective-C


I have an extension (of SCNVector3) in Swift like this:

extension SCNVector3 {

    // some functions extending SCNVector3 here....

}

I want to convert this extension to Objective-C. I know that the equivalent of extensions in ObjC is 'categories' but it doesn't seem possible to create a category on a struct like SCNVector3.

https://developer.apple.com/documentation/scenekit/scnvector3


Solution

  • There is no equivalent to Swift structs in Objective C. You should implement the extension's methods as C functions. For example computing the length of a vector:

    inline SCNVector3 ExtSCNVector3Subtract(SCNVector3 inA, SCNVector3 inB) {
        return SCNVector3Make(inA.x - inB.x, inA.y - inB.y, inA.z - inB.z);
    }
    
    inline float ExtSCNVector3Length(SCNVector3 inA) {
        return sqrtf(inA.x * inA.x + inA.y * inA.y + inA.z * inA.z);
    }
    

    How you name the functions is entirely up to your taste. You call it as follows:

    SCNVector3 a = ...;
    SCNVector3 a = ...;
    float distance = ExtSCNVector3Length(ExtSCNVector3Subtract(a, b));