Search code examples
swiftprogram-entry-pointswift-playground

Alternate for main function in swift?


I was playing around in Playground And I wondered Where is Main Function unlike in other languages , Swift does not have a main function , Whats the alternative or technique used to replace main function in swift when using in architecture outside that of Apple ( when used outside of ios and osx) since swift is soon going to be opensource ??


Solution

  • In a playground file, execution begins at the top of the playground file.

    If you wish, you can imagine an implicit func main() { just above the first reachable line and a } just below the last reachable line. But that's probably not constructive. Instead, it's better to just realize that not all languages need a main function, and Swift is one of those languages.

    For example, if we write a shell script, it will look something like this:

    mkdir workspace
    cd workspace
    git clone https://github.com/nhgrif/SQLConnect
    

    This is very simple... but there's no "main" function. Despite this, the terminal would be perfectly satisfied running this script, which would create a "workspace" directory and download my SQLConnect library into it.

    A playground file is executed in much the same way as many interpreted languages. You do not need a main function. Single .swift files that are executed via the swift command in the terminal are executed in the exact same way. They start at the top of the file and work their way down.