Search code examples
objective-cswiftnsarrayswift3

How do I convert Objective-C array of pointers to Swift?


In Objective-C these are two declarations of array of pointers:

NSArray<MTKMesh *> *mtkMeshes;
NSArray<MDLMesh *> *mdlMeshes;

I am struggling declaring the equivalent in Swift 3.0.


Solution

  • MTKMesh and MDLMesh are classes (reference types). A variable of type MTKMesh in Swift is a reference to an object instance, i.e. what a variable of type MTKMesh * is in Objective-C.

    Therefore you can simply declare

    var mtkMeshes: [MTKMesh] = []
    var mdlMeshes: [MDLMesh] = []
    

    Each element of the array is a reference to an object instance:

    let mesh1 = MDLMesh()
    let mesh2 = MDLMesh()
    mdlMeshes.append(mesh1)
    mdlMeshes.append(mesh1)
    mdlMeshes.append(mesh2)
    
    print(mdlMeshes[0] === mdlMeshes[1]) // true
    print(mdlMeshes[0] === mdlMeshes[2]) // false
    

    The first two array elements reference the same object instance, the last array element references a different instance. (=== is the "identical-to" operator).