Hello Triangle with Metal 4

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Drawing a triangle with Metal is more work than printing a line of text for a reason: nothing is drawn by default and almost nothing is implicit. You create the objects that talk to the GPU, describe the pipeline that turns vertices into pixels, record commands into a buffer, submit that buffer to a queue and tell the display when the result may be shown. Metal 4, introduced at WWDC25 for the 26 operating systems, keeps that shape but changes how each step is done: command buffers are reusable, their memory comes from allocators that you recycle per frame, resources are bound through argument tables and made resident through residency sets, and pipelines are compiled by an explicit compiler object. This page builds the same triangle twice, once with the Metal 4 types and once with the Metal 3 types, so you can see exactly what moved.

The facts were checked in November 2026. The versions documented are the Metal 4 core API (types prefixed MTL4, available from iOS, iPadOS, macOS, tvOS and visionOS 26.0) and, for the fallback path, the Metal 3 API that every Metal-capable device still supports. The Metal Shading Language is used at its 4.x level; MSL 4.1 and Xcode 27 belong to the 27 operating systems, and nothing on this page depends on a feature newer than MSL 4.0. Metal 4 needs an A14 Bionic or later (iPhone, iPad, Apple TV), a Mac with Apple silicon (M1 or later) or Apple Vision Pro; the code is Swift 6 and was written against the 26 SDKs. The Xcode setup, including the Metal Toolchain component, is covered in Setting Up Xcode and a Metal Project.

This is step 1 of the Metal Bookshelf running example: a multiplatform SwiftUI app that hosts an MTKView, takes the Metal 4 path when the device supports it and falls back to Metal 3 otherwise, and later gains a visionOS target. The triangle grows into a textured book, then the shelf, and so on. The concepts behind the stages are in The Rendering Pipeline and the reason Metal asks for so much explicit work is in Explicit vs Implicit APIs. What is new in the API as a whole is in What Is New in Metal 4.

What you will see

Storyboard of six panels: cleared window, flat coloured triangle, per-vertex colours, vertices read from a buffer, rotating triangle with per-frame data, and the Metal 3 fallback
Figure 1. The Bookshelf triangle, built up in six stages from a blank window to a validated Metal 3 fallback

The finished app shows a triangle with a red, a green and a blue corner that slowly rotates. The vertices are computed on the CPU every frame and written into a buffer, so the example exercises the part of a Metal renderer that matters most: data that changes per frame while the GPU is still reading the previous frame’s data.

The objects of a Metal 4 frame

Object graph: a device creates a command queue, command allocators, a command buffer and a compiler; the compiler produces a render pipeline state; buffers, an argument table and a residency set support the render command encoder; the MTKView supplies the drawable and render pass descriptor; a shared event synchronises CPU and GPU
Figure 2. The objects a Metal 4 renderer creates at launch and uses every frame
Object What it is Notes and options

MTLDevice

One GPU. On Apple silicon it is the only GPU and shares memory with the CPU.

Take it from MTKView.device (the view needs a device before it can create drawables) or call MTLCreateSystemDefaultDevice(). device.supportsFamily(.metal4) tells you whether the Metal 4 types work (MTLGPUFamily.metal4, 26.0).

MTL4CommandQueue

The queue you submit command buffers to. Created with device.makeMTL4CommandQueue().

Submitting happens through commit, so any thread can submit. It also owns the residency sets, the drawable wait and signal calls and event signals (see the sections below).

MTL4CommandAllocator

Memory in which commands are recorded. Created with device.makeCommandAllocator().

One per frame in flight. reset() frees the memory for reuse and may only be called after the GPU has finished every command buffer recorded with it. One command buffer at a time uses an allocator.

MTL4CommandBuffer

A list of commands. Created once with device.makeCommandBuffer() (not from a queue).

Reusable: call beginCommandBuffer(allocator:), encode, endCommandBuffer(), commit, and begin again. It does not retain the resources you encode, so you keep them alive yourself.

MTL4RenderPassDescriptor

Attachments, load and store actions for one render pass.

MTKView.currentMTL4RenderPassDescriptor returns one already pointing at the current drawable, configured the way currentRenderPassDescriptor is for Metal 3.

MTL4RenderCommandEncoder

Records the draw state and draw calls of one pass. Created with commandBuffer.makeRenderCommandEncoder(descriptor:options:).

options can be empty or contain .suspending and .resuming, which split one pass across several encoders (useful when several threads encode into one pass).

MTL4Compiler

Compiles shaders and pipelines. Created with device.makeCompiler(descriptor:).

Pipeline compilation is no longer hidden inside the device. It has synchronous and async entry points, and you can give it an MTL4CompilerDescriptor with a pipeline data set serializer for caching (see Shader Compilation and Pipeline Caching).

MTLRenderPipelineState

The compiled pipeline: shaders, vertex layout, attachment formats and blending.

The same type in Metal 3 and Metal 4. The Metal 4 path builds it from an MTL4RenderPipelineDescriptor; see The Metal Render Pipeline.

MTL4ArgumentTable

A small table of resource bindings for the stages of an encoder. Created with device.makeArgumentTable(descriptor:).

MTL4ArgumentTableDescriptor.maxBufferBindCount (and the texture and sampler counts) size the table; keep them as small as the shaders need, because the table’s footprint depends on them. You fill it with setAddress(_:index:) for buffers, setTexture and setSamplerState for resource IDs.

MTLResidencySet

A set of allocations the GPU may access. Created with device.makeResidencySet(descriptor:), available from iOS 18 and macOS 15.

Metal 4 does not track the resources you use for you. You add them to a set, commit() the set and add the set to the queue (or to a single command buffer with useResidencySet).

MTLSharedEvent

A counter signalled by the GPU and waited on by the CPU.

Signalled from the queue with signalEvent(_:value:) once a frame’s commands finish. The CPU waits for value - framesInFlight before reusing that frame’s allocator and buffers.

Two points that surprise people coming from Metal 3. First, the command buffer is not created from the queue and is not single-use: it is a long-lived object that you recycle. Second, nothing keeps your buffers and textures alive or resident for the GPU on your behalf: if a buffer is missing from a residency set (or from useResidencySet), the GPU may read memory that is not resident, which is why the sample code and the code below build a long-lived set at launch.

Choosing the Metal 4 path at runtime

An app that supports older systems cannot assume the MTL4 types exist. The check has two halves: the operating system must be 26 or later (a compile-time availability check) and the GPU must support the metal4 family.

import MetalKit

/// Creates the renderer that matches the device: Metal 4 when available, Metal 3 otherwise.
@MainActor
func makeRenderer(for view: MTKView) -> (any MTKViewDelegate)? {
    if #available(iOS 26.0, macOS 26.0, tvOS 26.0, visionOS 26.0, *),
       let device = view.device, device.supportsFamily(.metal4) {
        return Metal4Renderer(view: view)
    }
    return Metal3Renderer(view: view)
}

The two generations are independent type families, so one renderer class per generation is the cleanest structure for a hello-world; in a larger app you adopt Metal 4 piece by piece, because an MTL4CommandQueue and an MTLCommandQueue can synchronise through MTLEvent and MTLSharedEvent.

Project layout

The example has five files. Xcode’s Multiplatform App template provides the first; add the rest.

File Role

BookshelfApp.swift

The SwiftUI App that shows one TriangleView.

TriangleView.swift

A representable that creates the MTKView and keeps the renderer alive (explained in MetalKit, MTKView and SwiftUI).

ShaderTypes.h

C header shared by Swift and MSL: buffer indices and the vertex struct. Add it to the target and list it in the target’s Objective-C bridging header (see The Metal Shading Language).

Shaders.metal

The vertex and fragment functions. Xcode compiles every .metal file of the target into default.metallib.

Metal4Renderer.swift, Metal3Renderer.swift

The two renderers.

The shared header

Because the CPU writes vertices and the GPU reads them, both sides must agree on the layout. One header, included by Swift through the bridging header and by MSL through #include, is the single source of truth.

// ShaderTypes.h
#ifndef ShaderTypes_h
#define ShaderTypes_h

#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else
#import <Foundation/Foundation.h>
#endif

#include <simd/simd.h>

/// Slots in the argument table (Metal 4) or buffer slots (Metal 3).
typedef NS_ENUM(NSInteger, BufferIndex) {
    BufferIndexVertices = 0,
    BufferIndexViewport = 1
};

/// One vertex: a position in pixels measured from the centre of the view, and a colour.
typedef struct {
    vector_float2 position;   // offset 0, 8 bytes
    vector_float4 color;      // offset 16 (16-byte aligned), stride 32
} TriangleVertex;

#endif /* ShaderTypes_h */

Source: Apple: Drawing a triangle with Metal 4 (the sample’s ShaderTypes.h)

The vector_float2 followed by a vector_float4 leaves eight bytes of padding before color, so the stride is 32 bytes on both sides. Writing Float triples by hand on the Swift side is the classic way to get garbage colours, which is why the struct is imported from the header instead.

The shaders

// Shaders.metal
#include <metal_stdlib>
#include "ShaderTypes.h"
using namespace metal;

struct RasterizerData {
    float4 position [[position]];   // clip-space position, consumed by the rasteriser
    float4 color;                   // interpolated across the triangle
};

vertex RasterizerData triangleVertex(uint vertexID [[vertex_id]],
                                     constant TriangleVertex *vertices [[buffer(BufferIndexVertices)]],
                                     constant vector_uint2 &viewportSize [[buffer(BufferIndexViewport)]])
{
    RasterizerData out;
    // Convert from pixels (origin at the centre) to normalised device coordinates.
    float2 pixelPosition = vertices[vertexID].position;
    out.position = float4(pixelPosition / (float2(viewportSize) / 2.0), 0.0, 1.0);
    out.color = vertices[vertexID].color;
    return out;
}

fragment float4 triangleFragment(RasterizerData in [[stage_in]])
{
    return in.color;
}

The vertex function runs once per vertex and must produce a [[position]] in clip space. Metal divides clip-space x, y and z by w to get normalised device coordinates, where x and y run from -1 to +1 with y pointing up and the visible depth range is 0 to 1. Dividing a pixel offset by half the viewport size gives exactly that: \( x_{ ndc } = x_{ px } / (w / 2) \). The rasteriser then interpolates color between the three vertices and runs the fragment function for each covered pixel. Every attribute and address space used here is explained in The Metal Shading Language.

The Metal 4 renderer

The complete renderer. It follows Apple’s "Drawing a triangle with Metal 4" sample, written in Swift.

import MetalKit

/// How many frames the CPU may record while the GPU still works on earlier ones.
let maxFramesInFlight = 3

@available(iOS 26.0, macOS 26.0, tvOS 26.0, visionOS 26.0, *)
@MainActor
final class Metal4Renderer: NSObject, MTKViewDelegate {
    private let device: MTLDevice
    private let queue: MTL4CommandQueue
    private let commandBuffer: MTL4CommandBuffer
    private var allocators: [MTL4CommandAllocator] = []
    private let argumentTable: MTL4ArgumentTable
    private let residencySet: MTLResidencySet
    private let pipeline: MTLRenderPipelineState
    private var vertexBuffers: [MTLBuffer] = []
    private let viewportBuffer: MTLBuffer
    private let sharedEvent: MTLSharedEvent
    private var frameNumber: UInt64 = 0

    init?(view: MTKView) {
        guard let device = view.device,
              let queue = device.makeMTL4CommandQueue(),
              let commandBuffer = device.makeCommandBuffer(),
              let library = device.makeDefaultLibrary(),
              let sharedEvent = device.makeSharedEvent(),
              let viewportBuffer = device.makeBuffer(length: MemoryLayout<SIMD2<UInt32>>.stride,
                                                     options: .storageModeShared),
              let layer = view.layer as? CAMetalLayer else { return nil }
        sharedEvent.signaledValue = 0

        // One vertex buffer and one allocator per frame in flight.
        var buffers: [MTLBuffer] = []
        var frameAllocators: [MTL4CommandAllocator] = []
        for _ in 0..<maxFramesInFlight {
            guard let buffer = device.makeBuffer(length: 3 * MemoryLayout<TriangleVertex>.stride,
                                                 options: .storageModeShared),
                  let allocator = device.makeCommandAllocator() else { return nil }
            buffers.append(buffer)
            frameAllocators.append(allocator)
        }

        let table: MTL4ArgumentTable
        let residency: MTLResidencySet
        let state: MTLRenderPipelineState
        do {
            // Argument table with two buffer slots: vertices and viewport size.
            let tableDescriptor = MTL4ArgumentTableDescriptor()
            tableDescriptor.maxBufferBindCount = 2
            table = try device.makeArgumentTable(descriptor: tableDescriptor)

            // Residency set holding everything the GPU reads, added to the queue once.
            residency = try device.makeResidencySet(descriptor: MTLResidencySetDescriptor())
            residency.addAllocation(viewportBuffer)
            for buffer in buffers { residency.addAllocation(buffer) }
            residency.commit()
            queue.addResidencySet(residency)
            queue.addResidencySet(layer.residencySet)   // the view's drawables

            // Compile the render pipeline with a Metal 4 compiler.
            let compiler = try device.makeCompiler(descriptor: MTL4CompilerDescriptor())
            let descriptor = MTL4RenderPipelineDescriptor()
            descriptor.label = "Triangle pipeline"
            let vertexFunction = MTL4LibraryFunctionDescriptor()
            vertexFunction.library = library
            vertexFunction.name = "triangleVertex"
            let fragmentFunction = MTL4LibraryFunctionDescriptor()
            fragmentFunction.library = library
            fragmentFunction.name = "triangleFragment"
            descriptor.vertexFunctionDescriptor = vertexFunction
            descriptor.fragmentFunctionDescriptor = fragmentFunction
            descriptor.colorAttachments[0].pixelFormat = view.colorPixelFormat
            state = try compiler.makeRenderPipelineState(descriptor: descriptor,
                                                         dynamicLinkingDescriptor: nil,
                                                         compilerTaskOptions: nil)
        } catch {
            print("Metal 4 setup failed: \(error)")
            return nil
        }

        self.device = device
        self.queue = queue
        self.commandBuffer = commandBuffer
        self.sharedEvent = sharedEvent
        self.viewportBuffer = viewportBuffer
        self.vertexBuffers = buffers
        self.allocators = frameAllocators
        self.argumentTable = table
        self.residencySet = residency
        self.pipeline = state
        super.init()
        mtkView(view, drawableSizeWillChange: view.drawableSize)
    }

    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
        var viewport = SIMD2<UInt32>(UInt32(size.width), UInt32(size.height))
        viewportBuffer.contents().copyMemory(from: &viewport, byteCount: MemoryLayout<SIMD2<UInt32>>.stride)
    }

    func draw(in view: MTKView) {
        let next = frameNumber + 1
        let frameIndex = Int(next % UInt64(maxFramesInFlight))

        // 1. Make sure the GPU is done with the frame that used this allocator and buffer.
        if next > UInt64(maxFramesInFlight),
           !sharedEvent.wait(untilSignaledValue: next - UInt64(maxFramesInFlight), timeoutMS: 10) {
            return   // the GPU is behind: skip this frame instead of corrupting data in use
        }

        // 2. Get the drawable as late as possible.
        guard let drawable = view.currentDrawable,
              let passDescriptor = view.currentMTL4RenderPassDescriptor else { return }
        frameNumber = next

        // 3. Update this frame's vertices.
        let angle = Float(frameNumber % 360) * .pi / 180
        writeTriangle(into: vertexBuffers[frameIndex], angle: angle)

        // 4. Record.
        let allocator = allocators[frameIndex]
        allocator.reset()
        commandBuffer.beginCommandBuffer(allocator: allocator)
        commandBuffer.label = "Frame \(frameNumber)"

        guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescriptor) else {
            commandBuffer.endCommandBuffer()
            return
        }
        encoder.label = "Triangle pass"
        encoder.setViewport(MTLViewport(originX: 0, originY: 0,
                                        width: Double(view.drawableSize.width),
                                        height: Double(view.drawableSize.height),
                                        znear: 0, zfar: 1))
        encoder.setRenderPipelineState(pipeline)
        argumentTable.setAddress(vertexBuffers[frameIndex].gpuAddress,
                                 index: BufferIndex.vertices.rawValue)
        argumentTable.setAddress(viewportBuffer.gpuAddress,
                                 index: BufferIndex.viewport.rawValue)
        encoder.setArgumentTable(argumentTable, stages: .vertex)
        encoder.drawPrimitives(primitiveType: .triangle, vertexStart: 0, vertexCount: 3)
        encoder.endEncoding()
        commandBuffer.endCommandBuffer()

        // 5. Submit: wait for the drawable, run, signal the drawable, present, signal the event.
        queue.waitForDrawable(drawable)
        queue.commit([commandBuffer])
        queue.signalDrawable(drawable)
        drawable.present()
        queue.signalEvent(sharedEvent, value: frameNumber)
    }

    /// An equilateral triangle, rotated by `angle`, with a red, green and blue corner.
    private func writeTriangle(into buffer: MTLBuffer, angle: Float) {
        let radius: Float = 200
        let colors: [SIMD4<Float>] = [[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]
        let vertices = buffer.contents().bindMemory(to: TriangleVertex.self, capacity: 3)
        for i in 0..<3 {
            let a = angle + Float(i) * 2 * .pi / 3 + .pi / 2
            vertices[i] = TriangleVertex(position: [radius * cos(a), radius * sin(a)], color: colors[i])
        }
    }
}

The frame, step by step

sequenceDiagram participant V as MTKView participant R as Renderer participant Q as MTL4CommandQueue participant G as GPU V->>R: draw(in:) R->>R: wait on shared event for frame N minus 3 R->>V: currentDrawable, currentMTL4RenderPassDescriptor R->>R: write vertices, reset allocator, begin command buffer R->>R: encode pass, end encoding, end command buffer R->>Q: waitForDrawable R->>Q: commit command buffer R->>Q: signalDrawable R->>Q: signalEvent with frame number R->>V: drawable.present() Q->>G: run the command buffer G-->>Q: finished, event value becomes N G-->>V: drawable shown on the display
Figure 3. One Metal 4 frame between the app, the view, the queue and the GPU
  1. Wait for the frame that used these resources. The renderer owns three allocators and three vertex buffers. Frame N reuses the objects of frame N - 3, so it must wait until the queue signals value N - 3. When the GPU keeps up, the wait returns immediately. The 10 ms timeout in the sample only protects against a stalled GPU; skipping the frame is safer than touching data the GPU still reads.

  2. Obtain the drawable late. Reading currentDrawable takes one of a small pool of drawables from the layer and may block if all are in use. Do it right before encoding the pass that writes to it.

  3. Write per-frame data. Each frame has its own vertex buffer, so the CPU never writes bytes the GPU is still reading.

  4. Reset the allocator and begin the command buffer. reset() releases the memory recorded for the earlier use of this allocator; beginCommandBuffer(allocator:) makes the single command buffer record into it.

  5. Encode the pass. Pipeline, viewport and arguments are set on the encoder, then drawPrimitives. The argument table is copied into the command stream at draw time, so reusing one table across frames is fine as long as you set the entries before each draw that needs different values.

  6. Submit. waitForDrawable makes the queue wait until the drawable can be written, commit hands over the command buffers, signalDrawable tells the drawable the GPU has finished writing it and present() schedules it for the display. signalEvent then publishes the frame number to the CPU.

Options and parameters worth knowing

Call Parameter or option Effect

makeRenderCommandEncoder(descriptor:options:)

MTL4RenderEncoderOptions .suspending, .resuming

Lets one render pass be encoded by several encoders in sequence, so several threads can record one pass into separate command buffers.

beginCommandBuffer(allocator:options:)

MTL4CommandBufferOptions (logState)

Carries an MTLLogState for shader logging; the plain form is enough for most apps.

commit(_:options:)

MTL4CommitOptions

Optional commit options such as feedback; an array of command buffers is committed together.

MTL4ArgumentTableDescriptor

maxBufferBindCount, maxTextureBindCount, maxSamplerStateBindCount, initializeBindings, supportAttributeStrides

Sizes the table. A larger table costs more memory than a small one, so request only what the shaders bind.

setArgumentTable(_:stages:)

MTLRenderStages .vertex, .fragment, .object, .mesh, .tile

Chooses which stages read this table; the same table can serve several stages.

encoder.setViewport(_:)

MTLViewport

Maps NDC to pixels. Its originY is at the top, the opposite of NDC. znear and zfar map NDC depth 0 to 1 to the depth range.

encoder.setCullMode(_:), setFrontFacing(_:)

.back, .front, .none; .clockwise or .counterClockwise

The default is no culling and clockwise front faces, which is why the triangle appears with either winding. Turn culling on once you draw closed meshes.

The default MTLViewport of a render pass already covers the whole attachment, so setViewport is only required when you want a sub-rectangle; the sample sets it to make the data flow explicit.

The Metal 3 renderer

The Metal 3 version uses a command queue and a fresh command buffer per frame. Vertex data is small, so it goes in with setVertexBytes, which copies up to 4 KB straight into the command stream and removes the need for per-frame buffers. A semaphore limits the frames in flight.

import MetalKit

@MainActor
final class Metal3Renderer: NSObject, MTKViewDelegate {
    private let queue: MTLCommandQueue
    private let pipeline: MTLRenderPipelineState
    private let inFlight = DispatchSemaphore(value: maxFramesInFlight)
    private var viewportSize = SIMD2<UInt32>(1, 1)
    private var frameNumber: UInt64 = 0

    init?(view: MTKView) {
        guard let device = view.device,
              let queue = device.makeCommandQueue(),
              let library = device.makeDefaultLibrary() else { return nil }
        self.queue = queue

        let descriptor = MTLRenderPipelineDescriptor()
        descriptor.label = "Triangle pipeline"
        descriptor.vertexFunction = library.makeFunction(name: "triangleVertex")
        descriptor.fragmentFunction = library.makeFunction(name: "triangleFragment")
        descriptor.colorAttachments[0].pixelFormat = view.colorPixelFormat
        do {
            pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
        } catch {
            print("Metal 3 setup failed: \(error)")
            return nil
        }
        super.init()
        mtkView(view, drawableSizeWillChange: view.drawableSize)
    }

    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
        viewportSize = SIMD2<UInt32>(UInt32(size.width), UInt32(size.height))
    }

    func draw(in view: MTKView) {
        inFlight.wait()                        // at most maxFramesInFlight frames recorded ahead
        guard let commandBuffer = queue.makeCommandBuffer(),
              let passDescriptor = view.currentRenderPassDescriptor,
              let drawable = view.currentDrawable,
              let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescriptor) else {
            inFlight.signal()
            return
        }
        frameNumber += 1
        commandBuffer.addCompletedHandler { [inFlight] _ in inFlight.signal() }

        let angle = Float(frameNumber % 360) * .pi / 180
        var vertices = (0..<3).map { i -> TriangleVertex in
            let a = angle + Float(i) * 2 * .pi / 3 + .pi / 2
            let colors: [SIMD4<Float>] = [[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]
            return TriangleVertex(position: [200 * cos(a), 200 * sin(a)], color: colors[i])
        }
        var viewport = viewportSize

        encoder.setRenderPipelineState(pipeline)
        encoder.setVertexBytes(&vertices, length: MemoryLayout<TriangleVertex>.stride * 3,
                               index: BufferIndex.vertices.rawValue)
        encoder.setVertexBytes(&viewport, length: MemoryLayout<SIMD2<UInt32>>.stride,
                               index: BufferIndex.viewport.rawValue)
        encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
        encoder.endEncoding()

        commandBuffer.present(drawable)
        commandBuffer.commit()
    }
}
Two-column table comparing Metal 3 and Metal 4 calls for queue creation, command buffers, memory, encoders, pipelines, resource binding, residency, presentation and synchronisation
Figure 4. The same frame expressed with the Metal 3 and the Metal 4 calls

The differences, one by one:

  • Command buffer lifetime. Metal 3 creates a transient command buffer per frame from the queue; Metal 4 reuses one object and only the allocator memory changes.

  • Resource lifetime. Metal 3 retains every resource a command buffer references until it completes (unless you ask for unretained references); Metal 4 does not, and expects residency sets.

  • Binding. Metal 3 binds with setVertexBuffer, setVertexBytes and the like on the encoder. Metal 4 binds through an argument table, and the encoder has no setVertexBytes: small constants go into a buffer you own.

  • Presentation. Metal 3 calls commandBuffer.present(drawable) and the commit schedules it. In Metal 4 the queue brackets the commit with waitForDrawable and signalDrawable and the drawable presents itself.

  • Pacing. Metal 3 apps usually count frames with a semaphore signalled from a completed handler. Metal 4 samples signal a shared event from the queue and wait on it from the CPU, which also works across several queues.

The host view

A minimal host is enough to run both renderers. The next page, MetalKit, MTKView and SwiftUI, explains each choice in detail; the important point here is that MTKView.delegate is a weak reference, so something else must own the renderer.

import SwiftUI
import MetalKit

#if os(macOS)
typealias PlatformRepresentable = NSViewRepresentable
#else
typealias PlatformRepresentable = UIViewRepresentable
#endif

struct TriangleView: PlatformRepresentable {
    final class Coordinator {
        var renderer: (any MTKViewDelegate)?     // strong reference: MTKView.delegate is weak
    }
    func makeCoordinator() -> Coordinator { Coordinator() }

    private func makeView(_ context: Context) -> MTKView {
        let view = MTKView()
        view.device = MTLCreateSystemDefaultDevice()
        view.colorPixelFormat = .bgra8Unorm
        view.clearColor = MTLClearColor(red: 0.1, green: 0.1, blue: 0.12, alpha: 1)
        context.coordinator.renderer = makeRenderer(for: view)
        view.delegate = context.coordinator.renderer
        view.preferredFramesPerSecond = 60
        return view
    }

    #if os(macOS)
    func makeNSView(context: Context) -> MTKView { makeView(context) }
    func updateNSView(_ view: MTKView, context: Context) {}
    #else
    func makeUIView(context: Context) -> MTKView { makeView(context) }
    func updateUIView(_ view: MTKView, context: Context) {}
    #endif
}

@main
struct BookshelfApp: App {
    var body: some Scene {
        WindowGroup { TriangleView().ignoresSafeArea() }
    }
}

Source: Apple: MTKView

When the window stays blank

Symptom Likely cause What to check

Window shows only the clear colour

The pipeline draws nothing: wrong function names, a vertex outside clip space, or culling that removes the triangle

Function names in .name must match the .metal source exactly. Print the positions. Remove the cull mode while debugging.

Nothing at all, not even the clear colour

MTKView.device is nil or the delegate was released

Set the device before the renderer is created. Keep the renderer in a strong property (the coordinator above).

Crash or garbage colours

Swift and MSL disagree about the struct layout

Use the shared header, never hand-pack Float arrays. Check MemoryLayout<TriangleVertex>.stride equals 32.

Intermittent flicker or GPU errors under load

A buffer or allocator was reused while the GPU still used it

Count frames in flight: one buffer and one allocator per frame, and the wait before reuse.

Validation message about a resource not being resident

A buffer or texture used by a draw is not in a residency set

Add every long-lived resource to a set, commit the set, add it to the queue. Turn on Metal API validation in the scheme.

Metal 4 calls crash on an older device

The Metal 4 path was taken without the family check

Guard with #available and supportsFamily(.metal4); keep the Metal 3 renderer for older GPUs and systems.

makeDefaultLibrary() returns nil

The .metal file is not in the target, or the Metal Toolchain component is not installed

Check Target Membership and Xcode’s Components settings; see Setting Up Xcode and a Metal Project.

Turn on Metal API Validation and Shader Validation in the scheme’s Diagnostics while developing; they report most of the mistakes above as readable messages. Capturing a frame with the Metal debugger shows which pass, pipeline and buffers a draw used; see Debugging and Profiling Metal.

Performance notes

  • Frames in flight. Two or three is the usual range. More frames hide CPU jitter but add input latency; fewer make the CPU wait for the GPU. The page on pacing, Game Loop and Frame Timing, explains the trade-off.

  • Reuse, do not recreate. Command buffers, allocators, argument tables and pipelines are created once. Creating a pipeline per frame is the most expensive mistake a beginner can make.

  • Small argument tables. Bind counts set at creation cost memory per table and per encoder; request what the shaders use.

  • Shared storage on Apple silicon. .storageModeShared buffers live in memory the CPU and GPU both access, so writing vertices each frame needs no copy. Storage modes are covered in Buffers and Vertex Descriptors.

  • Drawable lifetime. Hold a drawable for as short a time as possible; do heavy CPU work before reading currentDrawable.

What changed recently

Version Change

iOS, macOS and the other 26 systems (2025)

Metal 4 core API: MTL4CommandQueue, MTL4CommandBuffer, MTL4CommandAllocator, MTL4ArgumentTable, MTL4Compiler, new barriers. Introduced at WWDC25 (session 205 and the Metal 4 core API documentation).

26.0

CAMetalLayer.residencySet and MTKView.currentMTL4RenderPassDescriptor make MetalKit views work with the Metal 4 queue.

26.4

MTKView.residencySet is available as an instance property of the view.

iOS 18 and macOS 15 (2024)

MTLResidencySet introduced; Metal 4 relies on it.

27 systems and Xcode 27 (2026)

MSL 4.1; Intel-specific storage and GPU families deprecated (MTLStorageMode.managed, MTLGPUFamily.mac2 and .common3), which matters for Mac apps that still target x86_64.

Where the books are out of date

Source Statement Today

Metal by Tutorials, 4th edition (chapters 1 and 3)

A new MTLCommandBuffer is created for every frame; the book targets Metal 3, Xcode 15, macOS 14 and iOS 17.

Still valid and supported. Metal 4 offers a reusable MTL4CommandBuffer, per-frame command allocators, argument tables and explicit residency, and the old model keeps working. The 5th edition (November 2025) moved to Swift 6 and the 26 SDKs but still teaches Metal 3. Xcode 27 needs an Apple-silicon Mac on macOS 26.6 or later.

Metal Programming Guide (Clayton), chapters 3 and 8

Written for Metal 2, Swift 4, Xcode 9 and iOS 11, with device.newDefaultLibrary() and an A7 baseline.

makeDefaultLibrary(), Swift 6.4 and Xcode 27; Metal 4 needs an A14, M1 or later, and the Metal 4 types above.