Binary inclusion (#embed in Swift)

Hi!

I wanted to know whether something like #embed (from C23) exists - would be nice to have in Swift on Linux (no .app-bundles) or on embedded.

Rust has it too - currently, I have to resort to the C++ interop, which introduces quite a few hassles

Thanks!

1 Like

This does not exist, but it has been discussed, albeit quite a long time ago:

The Clang that's linked into the Swift compiler currently does not have C23 support, so you also won't be able to use #embed directives through a C header import.

Further, the macro system runs macro plugins in a sandbox that does not have filesystem access, so you won't be able to build a custom macro that embeds the bytes of a file either. That'll have to be something done via a built-in macro. I think it would be a worthwhile addition especially for Embedded.

I can see it being quite useful in various ways—it'd be interesting to go a bit further than C and add type safety (something like #embed("config.json", decodingWith: JSONDecoder.self, as: MyConfiguration.self) I guess) although that would probably need to be implemented in Foundation.

It would be worth filing a GitHub issue for this feature.

4 Likes

SwiftPM 5.9 introduced an embedInCode rule.

The feature wasn't pitched or reviewed (as far as I know), and there's an open issue for type checking of larger resources.

It also uses Array rather than InlineArray, unlike the recently pitched Compile-Time Values and Section Placement Control.


For example, if your package manifest contains:

let package = Package(
  name: "…",
  products: […],
  targets: [
    .target(
      name: "…",
      resources: [.embedInCode("Example.txt")],

then a derived embedded_resources.swift file will contain:

struct PackageResources {
  static let Example_txt: [UInt8] = […]
}
5 Likes

It would also be cool to have support for embedding directories. In my opinion, this is something that Rust does right, look for example at these projects:

rust_embed is a crate that even allows me to compress my assets.

Where can I file such an issue?