Appendix A: Production Techniques

This appendix collects patterns for taking a shader from a demo into an app people use every day: reacting to touch and device motion, adjusting quality to the device's state, structuring reusable effects, and finding out where the time goes. The shader names in the snippets (touchResponse, glow, ripple) are placeholders for your own functions.

Interaction patterns

Touch response

A touch effect needs two values from Swift: where the finger is, and how strongly the effect should show (0 when idle, 1 while touching). The location can jump straight to the new value, but the strength should fade in and out.

withAnimation can't fade it on its own. SwiftUI doesn't interpolate shader arguments, so if you change a @State float inside withAnimation and pass it with .float(), the shader receives the final value on the next frame. To get the in-between values, put the argument in a modifier that conforms to Animatable. SwiftUI then interpolates animatableData and re-renders the modifier with each intermediate value.

struct TouchResponseEffect: ViewModifier, Animatable {
    var touchLocation: CGPoint
    var intensity: Float

    // SwiftUI interpolates this during withAnimation and calls body for each frame
    var animatableData: Float {
        get { intensity }
        set { intensity = newValue }
    }

    func body(content: Content) -> some View {
        content
            .visualEffect { [touchLocation, intensity] view, proxy in
                view.colorEffect(
                    ShaderLibrary.touchResponse(
                        .float2(proxy.size),
                        .float2(touchLocation),
                        .float(intensity)
                    )
                )
            }
    }
}

struct TouchResponsiveShader: ViewModifier {
    @State private var touchLocation: CGPoint = .zero
    @State private var touchIntensity: Float = 0

    func body(content: Content) -> some View {
        content
            .modifier(TouchResponseEffect(touchLocation: touchLocation, intensity: touchIntensity))
            .gesture(
                DragGesture(minimumDistance: 0)
                    .onChanged { value in
                        touchLocation = value.location
                        withAnimation(.easeOut(duration: 0.1)) {
                            touchIntensity = 1.0
                        }
                    }
                    .onEnded { _ in
                        withAnimation(.easeOut(duration: 0.5)) {
                            touchIntensity = 0
                        }
                    }
            )
    }
}

DragGesture reports locations in the view's local coordinate space, in points, with the origin at the top left. That is the same space the shader's position uses, so you can compare the two directly in Metal.

Gesture handling guidelines

  • Update the touch location on every onChanged call without animation. Any easing on the position makes the effect trail behind the finger.
  • Each frame lasts about 16.7 ms on a 60 Hz display and about 8.3 ms on a 120 Hz ProMotion display. Gesture handlers and the shader both have to fit inside that budget, so keep the Swift side to assigning a few values.
  • If you add haptics (for example with .sensoryFeedback), trigger them on the same state change that drives the shader so the tap and the visual land together.
  • DragGesture tracks one touch. For several fingers at once you need a different input source, such as a UIKit gesture recognizer bridged into SwiftUI, and you pass the points to the shader as an array (for example with .floatArray).

Motion integration with Core Motion

Device tilt makes a good input for holographic and parallax effects. This manager publishes the device's attitude (roll, pitch, yaw in radians) and user acceleration, ready to pass to a shader with .float3() after splitting the vector, or as separate .float() arguments.

class MotionManager: ObservableObject {
    @Published var rotation: SIMD3<Float> = .zero
    @Published var acceleration: SIMD3<Float> = .zero
    
    private let motionManager = CMMotionManager()
    private let queue = OperationQueue()
    
    func startMotionUpdates() {
        guard motionManager.isDeviceMotionAvailable else { return }
        
        motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
        motionManager.startDeviceMotionUpdates(to: queue) { [weak self] motion, error in
            guard let motion = motion else { return }
            
            DispatchQueue.main.async {
                self?.rotation = SIMD3<Float>(
                    Float(motion.attitude.roll),
                    Float(motion.attitude.pitch),
                    Float(motion.attitude.yaw)
                )
                self?.acceleration = SIMD3<Float>(
                    Float(motion.userAcceleration.x),
                    Float(motion.userAcceleration.y),
                    Float(motion.userAcceleration.z)
                )
            }
        }
    }
}

Call motionManager.stopDeviceMotionUpdates() when the view disappears. The sensors keep drawing power for as long as updates are running.

Performance optimization

Quality levels

A common approach is to define a few quality levels and pass the matching loop counts or sample counts to the shader as arguments. Pick the level from the device's current state rather than from its model: a new phone that is already hot needs the cheap path as much as an old one. ProcessInfo reports both the thermal state and Low Power Mode.

enum ShaderQuality: Int {
    case low = 0
    case medium = 1
    case high = 2
    case ultra = 3
    
    static func detectOptimal() -> ShaderQuality {
        let info = ProcessInfo.processInfo
        
        // The user asked the system to save battery
        if info.isLowPowerModeEnabled {
            return .low
        }
        
        switch info.thermalState {
        case .nominal: return .ultra
        case .fair: return .high
        case .serious: return .medium
        case .critical: return .low
        @unknown default: return .medium
        }
    }
    
    var shaderComplexity: ShaderComplexity {
        switch self {
        case .low:
            return ShaderComplexity(
                maxIterations: 4,
                sampleCount: 4,
                enableAdvancedEffects: false
            )
        case .medium:
            return ShaderComplexity(
                maxIterations: 8,
                sampleCount: 8,
                enableAdvancedEffects: true
            )
        case .high:
            return ShaderComplexity(
                maxIterations: 16,
                sampleCount: 16,
                enableAdvancedEffects: true
            )
        case .ultra:
            return ShaderComplexity(
                maxIterations: 32,
                sampleCount: 32,
                enableAdvancedEffects: true
            )
        }
    }
}

ShaderComplexity is your own struct. The numbers above are starting points to tune by profiling, not recommendations. Both values can change while the app runs, so re-check them when ProcessInfo.thermalStateDidChangeNotification or .NSProcessInfoPowerStateDidChange fires.

Precompiling shaders

SwiftUI compiles each shader for the GPU the first time it renders. That compile can delay the frame it happens in, which shows up as a hitch at the start of an animation. From iOS 18, Shader.compile(as:) lets you do it ahead of time, for example while the app launches:

@available(iOS 18.0, *)
func precompileShaders() async {
    // Argument values are placeholders, but their types must match the real call,
    // and the usage type must match how the shader is applied later.
    let shaders: [(Shader, Shader.UsageType)] = [
        (ShaderLibrary.touchResponse(.float2(CGSize.zero), .float2(CGPoint.zero), .float(0)), .colorEffect),
        (ShaderLibrary.ripple(.float2(CGPoint.zero), .float(0)), .layerEffect),
    ]
    
    for (shader, usage) in shaders {
        try? await shader.compile(as: usage)
    }
}

Call it from a .task on your root view. You don't need your own cache of Shader values: a Shader is a lightweight value holding the function name and arguments, and you create a new one every time the arguments change.

Profiling tools

  • Instruments, Metal System Trace template: a timeline of GPU work, useful to see whether a frame's GPU time fits the frame budget.
  • Instruments, Animation Hitches template: shows which frames missed their deadline and whether the delay was on the app side or in rendering.
  • Xcode's debug gauges: while the app runs from Xcode, the Debug navigator shows CPU and memory, plus FPS and GPU gauges when the app uses Metal.

Always profile on a real device. The Simulator renders on the Mac's GPU, so its timings tell you nothing about a phone.

Reusable architecture

A protocol for shader effects

Once an app has more than a handful of effects, a small protocol keeps them consistent: each effect has a name, default parameters, a way to build its Shader, and a modifier to apply it.

protocol ShaderEffect {
    associatedtype Parameters
    associatedtype Modifier: ViewModifier
    
    static var name: String { get }
    static var defaultParameters: Parameters { get }
    
    func shader(with parameters: Parameters) -> Shader
    func modifier(with parameters: Parameters) -> Modifier
}

// Example implementation
struct GlowEffect: ShaderEffect {
    static let name = "glow"
    static let defaultParameters = GlowParameters()
    
    struct GlowParameters {
        var radius: Float = 10.0
        var intensity: Float = 1.0
        var color: Color = .white
    }
    
    func shader(with parameters: GlowParameters) -> Shader {
        ShaderLibrary.glow(
            .float(parameters.radius),
            .float(parameters.intensity),
            .color(parameters.color)
        )
    }
    
    func modifier(with parameters: GlowParameters) -> some ViewModifier {
        GlowModifier(parameters: parameters)
    }
}

The Modifier associated type is there because a protocol requirement can't return some ViewModifier directly. Each conforming type still writes some ViewModifier, and Swift infers Modifier from it. GlowModifier is the view modifier that applies the shader.

Remember that .color() arguments arrive in Metal as premultiplied half4 values. A 50% transparent white comes in as half4(0.5, 0.5, 0.5, 0.5).

Component library structure

One way to lay out a reusable set of effects in Swift:

ShaderComponents/
├── Effects/
│   ├── GlowEffect.swift
│   ├── BlurEffect.swift
│   └── DistortionEffect.swift
├── Materials/
│   ├── GlassMaterial.swift
│   ├── MetalMaterial.swift
│   └── FabricMaterial.swift
├── Animations/
│   ├── PulseAnimation.swift
│   ├── WaveAnimation.swift
│   └── MorphAnimation.swift
└── Utilities/
    ├── ShaderPrecompile.swift
    ├── PerformanceMonitor.swift
    └── DeviceCapabilities.swift

Appendix B covers how to organize the .metal side.

Debugging

Seeing what the shader computes

You can't set a breakpoint inside a SwiftUI shader or print from it. The usual technique is to return an intermediate value as a color. To check a distance, return half4(half3(d), 1.0). To check a coordinate, return half4(half2(uv), 0.0, 1.0) and read the red and green channels. Black means 0 and white means 1. Values above 1 clip to white and negative values clip to black, so scale or offset first if you expect values outside that range.

Keep debug switches out of release builds. An environment variable read with ProcessInfo.processInfo.environment["SHADER_DEBUG"] (set in the scheme's Run settings) or an #if DEBUG block works for toggling a debug color mode passed to the shader as a .float().

Common performance issues

  • Too many samples. Every layer.sample() reads memory. A blur with 16 taps per pixel does 16 reads for every pixel of the view. Reduce the tap count, or blur at a lower radius.
  • Divergent branches. Pixels are processed in groups that run the same instruction together. When pixels in one group take different sides of an if, the group runs both sides. A branch on a uniform argument (the same for every pixel, like mode) is cheap because every pixel goes the same way.
  • Too many live values. Each pixel's work keeps its variables in registers. Large local arrays or many values alive at once can reduce how many pixels the GPU works on in parallel.
  • Large layer effects. layerEffect and distortionEffect render the view into an offscreen layer first. A full-screen layer effect costs more than the same effect on a small card.