Allow compiler control statements in container literals

While reading the implementation of SE-301, I noticed this snippet of code:

public struct SwiftPackageTool: ParsableCommand {
    private static let subcommands: [ParsableCommand.Type] = {
        var subcommands: [ParsableCommand.Type] = [
            Clean.self,
            PurgeCache.self,
            // ...
            ArchiveSource.self,
            CompletionTool.self,
        ]
        #if BUILD_PACKAGE_SYNTAX
        subcommands.append(contentsOf: [
            AddDependency.self,
            AddTarget.self,
            AddProduct.self,
        ])
        #endif
        return subcommands
    }()
    
    // ...
}

It got me thinking: Wouldn't it be more readable and structurally a lot cleaner, if compiler control statements are allowed in array/container literals:

public struct SwiftPackageTool: ParsableCommand {
    private static let subcommands: [ParsableCommand.Type] = [
        Clean.self,
        PurgeCache.self,
        // ...
        ArchiveSource.self,
        CompletionTool.self,
        
        #if BUILD_PACKAGE_SYNTAX
        AddDependency.self,
        AddTarget.self,
        AddProduct.self,
        #endif
    ]
    
    // ...
}

This is probably not possible for multi-line string literals, the other "scope-y" literals:

let someText = """
    This line exists for all platforms.
    #if os(Linux) // would be ambiguous whether this is a statement or part of the string
    This line exists for linux platforms only.
    #endif
    """

Although, string literals can just use interpolation instead:

let someText = """
    This line exists for all platforms.
    \(#if os(Linux)
    "This line exists for linux platforms only."
    #endif)
    """
1 Like

There's also an even more recent thread which for some reason I can't find at the moment.

3 Likes

Probably this one?

5 Likes