Is it safe to use ResultBuilders in Package.swift?

Supposing that you add the following codeblock to the Package.swift file:

@resultBuilder
enum ArrayBuilder<Element> {
    public static func buildEither(first elements: [Element]) -> [Element] {
        elements
    }

    public static func buildEither(second elements: [Element]) -> [Element] {
        elements
    }

    public static func buildOptional(_ elements: [Element]?) -> [Element] {
        elements ?? []
    }

    public static func buildExpression(_ expression: Element) -> [Element] {
        [expression]
    }

    public static func buildExpression(_: ()) -> [Element] {
        []
    }

    public static func buildBlock(_ elements: [Element]...) -> [Element] {
        elements.flatMap { $0 }
    }

    public static func buildArray(_ elements: [[Element]]) -> [Element] {
        Array(elements.joined())
    }
}

func buildTargets(@ArrayBuilder<Target?> targets: () -> [Target?]) -> [Target] {
    targets().compactMap { $0 }
}

This allows the following use of defining targets. I just doubt whether it's safe.

let package = Package(
    name: "DumpKit",
    platforms: [.iOS(.v17), .macOS(.v14), .watchOS(.v10)],
    products: [
        ......
    ],
    targets: buildTargets {
        #if os(OSX)
        Target.target(
            name: "PizzaKitFrontendTests",
            path: "Source/Path-Mac"
        )
        #elseif os(iOS)
        Target.target(
            name: "PizzaKitFrontendTests",
            path: "Source/Path-iOS"
        )
        #endif
    }
)

For what it's worth, I've been using result builders in my projects' package manifests for a few years without issue.

3 Likes