Appendix B: Shader Library Organization

This appendix covers how to organize a growing set of .metal files: folder layout, naming, sharing helper code, guarding against bad inputs, and documenting and versioning shaders.

File structure

How Xcode builds your shaders

Xcode compiles every .metal file in an app target into one library, default.metallib, inside the app bundle. ShaderLibrary.default (and the shorthand ShaderLibrary.myFunction) looks functions up by name in that library. Two consequences follow:

  • Folders are only for you. The compiler doesn't care which folder or file a function lives in.
  • Function names share one namespace. Two [[ stitchable ]] functions called glow in different files cause a build error, so names must be unique across the whole target.

Shaders in a Swift package go into the package's own bundle. Load them with ShaderLibrary.bundle(.module) instead of ShaderLibrary.default.

MyApp/
├── Shaders/
│   ├── Core/
│   │   ├── Math.h             // Shared math helpers (inline functions)
│   │   ├── Noise.h            // Noise functions
│   │   └── Color.h            // Color space conversions
│   ├── Effects/
│   │   ├── Blur.metal
│   │   ├── Glow.metal
│   │   └── Distortion.metal
│   ├── Materials/
│   │   ├── Glass.metal
│   │   ├── Metal.metal
│   │   └── Fabric.metal
│   └── UI/
│       ├── Buttons.metal
│       ├── Cards.metal
│       └── Backgrounds.metal

The shared code lives in headers because each .metal file compiles on its own. A helper defined in Math.metal isn't visible from Blur.metal. Put helpers in a header as inline functions and include it where you need it:

// Core/Math.h
#pragma once
#include <metal_stdlib>
using namespace metal;

inline float remap(float value, float inMin, float inMax, float outMin, float outMax) {
    return outMin + (value - inMin) / (inMax - inMin) * (outMax - outMin);
}
// Effects/Blur.metal
#include "../Core/Math.h"

The quoted include path is relative to the file doing the including. Headers aren't compiled on their own, so they don't need to be members of the target.

You don't need a bridging header or a shared ShaderTypes.h for SwiftUI shaders. Stitchable functions only receive the argument types SwiftUI supports (float, float2, float3, float4, colors, images and float arrays). The exception is raw bytes passed with .data(): if you pack a struct that way, a header shared by both sides keeps the layouts in sync.

Naming conventions

// Function naming pattern: categoryTypeVariant
[[ stitchable ]] half4 uiButtonGlow(...)
[[ stitchable ]] half4 materialGlassFrosted(...)
[[ stitchable ]] half4 effectBlurGaussian(...)

// Parameter naming
float time              // Animation time, in seconds since the effect started
float2 position         // Current pixel position, in points
float2 size            // View size, in points
float2 center          // Effect center point
float intensity        // Effect strength (0-1)
float radius           // Effect radius

A category prefix keeps related shaders together in autocomplete and avoids name collisions in the shared namespace. Using the same names for the same kinds of parameters across every shader means you can read any of them without checking what t or s stands for.

Parameter validation

A shader has no error reporting. A negative radius or an intensity of 40 doesn't throw: it draws garbage, or produces NaN values that show up as black or flickering pixels. Guard inputs on both sides.

Swift-side validation

Clamp values when they're set, so out-of-range values never reach the GPU:

struct ShaderParameters {
    var intensity: Float {
        didSet { intensity = max(0, min(1, intensity)) }
    }
    
    var radius: Float {
        didSet { radius = max(0, radius) }
    }
    
    var colorComponents: SIMD3<Float> {
        didSet { colorComponents = colorComponents.clamped(lowerBound: .zero, upperBound: .one) }
    }
    
    func validate() -> Bool {
        guard intensity >= 0 && intensity <= 1 else { return false }
        guard radius >= 0 else { return false }
        guard all(colorComponents .>= 0) && all(colorComponents .<= 1) else { return false }
        return true
    }
}

didSet doesn't run during initialization, which is why validate() is there: call it after creating the struct from external data (user settings, a JSON file).

Metal-side safety

Even with Swift-side checks, clamp inside the shader. It costs almost nothing and protects you when someone calls the shader from new code later.

// Always clamp inputs to valid ranges
float safeIntensity = saturate(intensity);
float safeRadius = max(0.0, radius);
float2 safeUV = clamp(uv, 0.0, 1.0);

// Prevent division by zero (assumes b >= 0, e.g. a length or a size)
float safeDivide(float a, float b) {
    return a / max(b, 0.0001);
}

// Safe normalization
float3 safeNormalize(float3 v) {
    float len = length(v);
    return len > 0.0001 ? v / len : float3(0, 0, 1);
}

saturate(x) is shorthand for clamp(x, 0.0, 1.0). normalize of a zero vector divides by zero and returns NaN, which is why safeNormalize falls back to a fixed direction.

Documentation

Shader parameters have no labels at the call site. ShaderLibrary.materialGlass(.float2(size), .float(1.5), .float(0.3), .color(tint)) doesn't say which float is which, and getting the order wrong compiles without complaint. Document the parameters in order on both sides.

Metal documentation template

/**
 * Creates a glass material effect with refraction and reflection
 *
 * @param position     Current pixel position in the view's coordinate space, in points
 * @param layer        Input layer for refraction sampling
 * @param size         View size in points
 * @param ior          Index of refraction (1.0-2.0, glass=1.5)
 * @param thickness    Glass thickness for chromatic aberration (0.0-1.0)
 * @param tint         Glass color tint (premultiplied alpha, as SwiftUI passes .color())
 *
 * @return Modified color with glass effect applied
 *
 * @performance O(n) where n is blur sample count
 * @quality Requires iOS 17.0+
 */
[[ stitchable ]] half4 materialGlass(
    float2 position,
    SwiftUI::Layer layer,
    float2 size,
    float ior,
    float thickness,
    half4 tint
) {
    // Implementation
}

A shader that takes SwiftUI::Layer needs #include <SwiftUI/SwiftUI_Metal.h> at the top of the file.

Swift documentation

/// A glass material effect that simulates realistic light refraction
///
/// This effect creates a convincing glass appearance by:
/// - Calculating Fresnel reflections based on viewing angle
/// - Applying chromatic aberration for thickness variation
/// - Sampling the background with refraction offsets
///
/// - Parameters:
///   - ior: Index of refraction (1.0-2.0). Common values:
///     - Water: 1.33
///     - Glass: 1.5
///     - Diamond: 2.42
///   - thickness: Simulated glass thickness affecting color separation
///   - tint: Color tint applied to the glass
///
/// - Performance: Heavy effect, consider using on small views only
/// - Complexity: O(n) where n is sample count
public struct GlassMaterial: ViewModifier {
    let ior: Float
    let thickness: Float
    let tint: Color
}

Versioning

Changing a shader's signature

Because every stitchable function lives in the one default library, the simplest way to change a shader's parameters without breaking existing callers is to add a new function under a new name and keep the old one until nothing calls it:

// Original: (position, color, size, radius)
[[ stitchable ]] half4 effectGlow(float2 position, half4 color, float2 size, float radius) { ... }

// New parameter order and a blend mode argument
[[ stitchable ]] half4 effectGlowV2(float2 position, half4 color, float2 size, float radius, float blendMode) { ... }

Move call sites over one at a time, then delete effectGlow. Searching the project for ShaderLibrary.effectGlow( finds every remaining caller.

Migrating stored parameters

If you save effect parameters (in user presets, for example), a migration step converts old saved values to the new layout:

protocol ShaderMigration {
    associatedtype OldParameters
    associatedtype NewParameters
    
    static func migrate(_ old: OldParameters) -> NewParameters
}

struct GlowEffectMigration_v1_to_v2: ShaderMigration {
    static func migrate(_ old: GlowParameters_v1) -> GlowParameters_v2 {
        GlowParameters_v2(
            radius: old.radius,
            intensity: old.intensity,
            color: old.color,
            blendMode: .normal  // New parameter with default
        )
    }
}