Search code examples
swiftassetsmetalmetalkit

Swift MetalKit unknknown return type MTKMesh.newMeshes


Up until now I have been following a tutorial (released around the time of Metal 1), to learn Metal. I haven't encountered any errors I couldn't figure out until this point. I am trying to execute this code

var meshes: [AnyObject]?
//code
let device = MTLDevice() //device is fine
let asset = MDLAsset() //asset works fine
do{
    meshes = try MTKMesh.newMeshes(asset: asset, device: device)
} catch //...

The error i'm getting is Cannot assign value of type '(modellOMeshes: [MDLMesh], metalKitMeshes: [MTKMesh])' to type '[AnyObject]?'

What is type of MTKMesh.newMeshes, and how can I store it in a variable? I tried casting it as! [AnyObject], but then xcode tells me that this cast would fail every time.


Solution

  • The return type of that method is ([MDLMesh], [MTKMesh]), a tuple comprised of an array of MTLMeshes and an array of MTKMeshes. The reason for this is that you might want the original collection of MDLMesh objects contained in the asset, in addition to the MTKMesh objects that are created for you.

    So, you can declare meshes like this:

    var meshes: ([MDLMesh], [MTKMesh])
    

    Or, if you don't care about the original MDLMeshes, you can "destructure" the tuple to get just the portion you care about into a variable of type [MTKMesh]:

    var meshes: [MTKMesh]
    (_, meshes) = try MTKMesh.newMeshes(asset: asset, device: device)