Search code examples
iosxcodeswiftuixcode-previews

Xcode preview error "Compiling failed: cannot find 'SomeView' in scope"


Xcode (15.4) preview compilation is weird. The following code compiles flawlessly for device or simulator, but fails if compiling for preview:

import SwiftUI

enum Namespace {
    struct View1: View {
        var body: some View {
            Text("Test")
        }
    }
}

extension Namespace {
    struct View2: View {
        var body: some View {
            View1() // Error only if compiling for preview
                    // CompileDylibError: Failed to build ViewX.swift
                    // Compiling failed: cannot find 'View1' in scope
        }
    }
}

#Preview {
    Namespace.View2()
}

What's going on here? Why compilation for preview is special?

So far I found two workarounds, either replace View1() with Namespace.View1() or add fileprivate typealias View1 = Namespace.View1, but keeping those in sync quickly gets annoying. Do you have better ideas?


Solution

  • Turns out it's bug which is fixed in Xcode 16.

    Fixed: Previewing inside of files with methods of types nested in extensions no longer fails. (74739568) (FB9019661)