SwiftUI Previews broken on Swift Package with dependencies

Hello!

Previously, using content from one Swift Package in the UI of another would cause preview failures. Now, with Xcode 16, this issue has been improved, and the preview feature is working, though occasional crashes still occur. I have submitted a report regarding this issue.

I’ve encountered some issues while developing a SwiftUI-based application, particularly when using Xcode’s SwiftUI preview feature, which frequently crashes.

My app supports both macOS and iOS. Due to the differences between the platforms, I’ve had to implement some pages using UIKit and reference a few UIKit-based open-source frameworks. For instance, I’m using the LazyPager library, which only supports iOS. During runtime, I ensure LazyPager is only compiled for iOS by using .product(name: "LazyPager", package: "LazyPager", condition: .when(platforms: [.iOS])), which works as expected.

However, when I use Xcode’s SwiftUI preview mode and select macOS as the target, UIKit-related code still gets compiled, leading to a crash, with the error message indicating an issue related to LazyPager's UIKit dependencies.

Since it’s not feasible to ask the maintainers of these open-source libraries to add #if canImport(UIKit) conditionals to their code, I would like to ask if there’s a better way to resolve this issue, ensuring that SwiftUI preview works properly on macOS.

If you have any suggestions or solutions, I would greatly appreciate your assistance. Thank you so much for your help!

import PackageDescription

let package = Package(
    name: "ImportLibrary",
    platforms: [
        .iOS(.v16),
        .macOS(.v13)
    ],
    products: [
        .library(
            name: "ImportLibrary",
            targets: ["ImportLibrary"]),
    ],
    dependencies: [
        .package(url: "https://github.com/gh123man/LazyPager", from: "1.1.0"),
    ],
    targets: [
        .target(
            name: "ImportLibrary",
            dependencies: [
                "SwiftSoup",
                "Kingfisher",
                "WaterfallGrid",
                .product(name: "LazyPager", package: "LazyPager", condition: .when(platforms: [.iOS])),
                "QuickModule"
            ]
        ),
        .testTarget(
            name: "ImportLibraryTests",
            dependencies: ["ImportLibrary"]),
    ]
)

Sincerely,
Best regards

SwiftUI Previews broken on Swift Package with dependencies
 
 
Q