How to pass data from the vertex to the fragment shader in Metal

Oscar de la Hera Gomez
Three flowers that represent Swift, Metal and XCode with the text "Pass Data from the Vertex to the Fragment Function in a Metal Shader" beneath it.

A step by step tutorial on implementing a MTKView in a UIView that passes data from the vertex function to the fragment function in a metal shader.

We recommend that you clone our Open Source Swift Starter Project, checking out the main branch and carrying out the steps below. The changes can be found on the tutorial/metal/pass-data-within-shader branch.

git clone git@github.com:delasign/swift-starter-project.git

Step One: Setup the MTKView

A screenshot of an iPhone showing a black background with a red triangle that was produced with metal.

Follow the tutorial below to setup a MTKView within a UIView that shows a triangle.

Step Two: Update the Metal Shader

A screenshot of Xcode showing the metal shader code provided below. The code uses comments to detail the changes that have to be carried out to allow the shader to pass data between the vertex and the fragment functions within a metal shader.

Update the metal shader to:

  • Include a struct (VertexOut) that defines the data that will be passed from the vertex function to the fragment function. This struct must include a float4 position [[position]]; for the vertex function to have a valid return type.
  • Update the return type of the vertex function to VertexOut.
  • Create and return the VertexOut within the vertex function.
  • Add the vertex out as an argument for the fragment function using code similar to VertexOut vertexOut [[stage_in]].
  • Update the fragment function to use the data from the vertexOut.

Step Three: Test

A screenshot of an iPhone showing how the triangle is now half white and half white, demonstrating that the data is correctly passed between the vertex function and the fragment function.

Run the code on a device and confirm that you see a triangle similar to the one above.

Looking to learn more about things you can do with Swift, Metal and XCode ?

Search our blog to find educational content on learning how to use Swift, Metal and XCode.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details