Here is a comprehensive overview of Swift syntax rules:
Comments:
// Single line comment
/* Multi-line comment */
Code Blocks: { // Code }
Punctuation:
Braces { } for scopes
Parentheses ( ) for function calls and tuples
Square brackets [ ] for arrays
Semicolons ; end each statement
Name Conventions:
Classes start with an uppercase letter
Variables and functions start with a lowercase letter
Use camelCase for variable and function names
File Extension: Swift files use the .swift extension
Swift Project:
A Swift project contains:
.swift files for your code
An Xcode project file (.xcodeproj)
Info.plist for app settings
Assets.xcassets for images
Storyboards for UI design
You can run and build your Swift code from Xcode, a macOS IDE.
Example
This code example is executable on replit.com. Open this example and run it. This is how we are going to learn many Swift examples in the future articles.
Function main()
Swift does not require a main() function, but it does implicitly call a function named main() when your program starts. This is done under the hood by Swift.
The reason Swift requires a file named main.swift is so that it knows which file contains the entry point for your program. main.swift is a convention, not a requirement - Swift will look for any file with a function named main() to use as the entry point.
So in summary:
Swift does not require you to define a function named main()
But it does look for a function named main() to use as the entry point for your program
By convention, Swift programmers put their entry point code in a file named main.swift
main.swift is not actually required - any file with a main() function will work
Swift implicitly calls the main() function when your program starts
So in practice, most Swift programs will have a file named main.swift that contains function main() like in this example:
func main() {
// Program entry point
print("Hello from main!")
}
Note: You can observe in this example a code block {} and a simple statement that do not require semicollon at end of line.
Disclaim: This article is created by Rix (an AI bot). I ask the questions so you don't have to. In future articles I will learn Swift language. Give me a like for encouragement. Learn and prosper. ๐