Basic Structure of Swift Program
At first, we consider a simple application that displays a line of text.
prinln("Welcome to Webeduclick!")
Output:
Welcome to Webeduclick!
It shows that the program displays the output text Welcome to Webeduclick!
1. Swift Code Files: Unlike C-based programming languages, Swift doesn’t have a main function or method. Rather, in an Xcode project, the file that contains the entry point for a Swift app must be named main.swift – code files end with the .swift filename extension. Any globally scoped statements in main.swift that are statements that are not written inside function, method or type definitions – serve as the app’s entry point.
2. Commenting Your Programs: The compiler ignores comments. Our convention is to begin every program with a comment that includes the figure number and purpose of the program. The comment begins with // indicating that it’s a single-line comment. It terminates at the end of the line on which the // appears. The single-line comment also can begin in the middle of a line, possibly after some code, and continue until the end of that line.
Swift also has multiline comments, which can be spread over several lines as in
/* This is a multiline comment.
Welcome to Swift Programming! */
These begin and end with the delimiters, /* and */. The compiler ignores all text between the delimiters.
3. Performing Output with Function println: Function println displays a line of text to the standard output. This is one of the Swift Standard Library’s global functions. Where the standard output appears depends on the type of program and where you execute it.
4. Semicolon not required in Swift: A program typically contains one or more statements that perform its task. Unlike other C-based programming languages, Swift statements are not required to end with a semicolon (;), though you can use them if you like. If you place more than one statement on the same line, they must be separated by semicolons.
5. Executing the Application: The above example is provided as a playground, so it executes immediately when you load it. If you enter the code into a playground, the application executes as you complete each statement. The results of any output statements are visible only if you show the Assistant Editor in the playground.
6. Compilation and Syntax Errors: As you write code in a playground or a [no-highlight].swift[/no-highlight] file that’s part of an Xcode project, the compiler continuously compiles your code. Any compilation errors are indicated by a red-stop-sign-shaped symbol displayed to the left of the lines of code in which the errors occur. You can click the symbols to view the error message that applies to your code.