Can there be multiple main entries?

I know logically there can be only one main entry in a program. But I have a git repository where I want to create different examples of Swift code, and to be able to run each example separately, thus the need for more main entries.

Any ideas as to how I could proceed?

It's a bit different depending if you're using native SPM, or Xcode projects.

In both cases, you'll need to create multiple targets. Each target produces a separate executable, each of which will have one entry point.

The distinction comes in how you share the non-@main related code.

In SPM you would create a library with all the shared code, and make that library a dependency of all of your executable targets.

In Xcode, you can make describe target membership on a per-file level. This is usually pretty tedious and annoying, but in this case it means that each target can contain every file, except for the files that define the other @main entry points.

1 Like

You might want to check out “Swift Snippets”. This is an upcoming feature of the Swift Package Manager that is available in nightly toolchain builds.

Your code shouldn't have a main entry point. Create a library with public functions. Then, a user can depend on the library and choose which function to run.

See Argument Parser for an example on providing multiple different example targets in a Swift Package Manager project.