Creating a console app. in Swift (on Linux)(part 2)

In my post Creating a console app. in Swift (on Linux) I demonstrated creating a console app. using Swift. I used top level statement to create the application, but there’s another way.

Note: Those familiar with C# will see how C# now offers both the traditional class based Program as well as top level statement style, well Swift offers similar.

After creating your application using

swift package init --type executable

Create a file in the Sources folder named App.swift or whatever you like except I found that main.swift didn’t seem to work and caused errors such as error: ‘main’ attribute cannot be used in a module that contains top-level code.

Now in your App.swift paste the following

@main
struct App {
    static func main() {
        print("Hello World")
    }
}

Note: The @main attribute is important to mark the type as the main application code.

If you now use the following from the command line, you should see Hello World output.

swift run