- Swift Tutorial
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Variables
- Swift - Constants
- Swift - Literals
- Swift - Comments
- Swift Operators
- Swift - Operators
- Swift - Arithmetic Operators
- Swift - Comparison Operators
- Swift - Logical Operators
- Swift - Assignment Operators
- Swift - Bitwise Operators
- Swift - Misc Operators
- Swift Advanced Operators
- Swift - Operator Overloading
- Swift - Arithmetic Overflow Operators
- Swift - Identity Operators
- Swift - Range Operators
- Swift Data Types
- Swift - Data Types
- Swift - Integers
- Swift - Floating-Point Numbers
- Swift - Double
- Swift - Boolean
- Swift - Strings
- Swift - Characters
- Swift - Type Aliases
- Swift - Optionals
- Swift - Tuples
- Swift - Assertions and Precondition
- Swift Control Flow
- Swift - Decision Making
- Swift - if statement
- Swift - if...else if...else Statement
- Swift - if-else Statement
- Swift - nested if statements
- Swift - switch statement
- Swift - Loops
- Swift - for in loop
- Swift - While loop
- Swift - repeat...while loop
- Swift - continue statement
- Swift - break statement
- Swift - fall through statement
- Swift Collections
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift Functions
- Swift - Functions
- Swift - Nested Functions
- Swift - Function Overloading
- Swift - Recursion
- Swift - Higher-Order Functions
- Swift Closures
- Swift - Closures
- Swift-Escaping and Non-escaping closure
- Swift - Auto Closures
- Swift OOps
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift-Overriding
- Swift - Initialization
- Swift - Deinitialization
- Swift Advanced
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Error handling
- Swift - Concurrency
- Swift - Type Casting
- Swift - Nested Types
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift - Function vs Method
- Swift - SwiftyJSON
- Swift - Singleton class
- Swift Random Numbers
- Swift Opaque and Boxed Type
- Swift Useful Resources
- Swift - Compile Online
- Swift - Quick Guide
- Swift - Useful Resources
- Swift - Discussion
Swift - Basic Syntax
If the Swift is installed successfully it will show the latest version of Swift. Swift is a powerful and expressive language to develop applications for Apple’s devices. It is designed to be easy to read, write and maintain. It also supports object-oriented and functional programming paradigms.
Syntax
Its syntaxes are much more clear, concise and easy to read. Now let us now see the basic structure of a Swift program, so that it will be easy for you to understand the basic building blocks of the Swift programming language.
/* My first Swift program */ var myString = "Hello, World!" print(myString)
Following is the output of the above program −
Hello, World!
Now let us learn what are the basic syntaxes and how you can use them in your Swift program.
Import Statement
You can use the import statement to import any Objective-C framework or C library) or Swift library directly into your Swift program. For example, the import cocoa statement makes all Cocoa libraries, APIs, and runtimes that form the development layer for all of OS X, available in Swift. Cocoa is implemented in Objective-C, which is a superset of C, so it is easy to mix C and even C++ into your Swift applications.
Syntax
Following is the syntax of the import statement −
import frameworkName or LibraryName
Example
import Foundation
Tokens
A Swift program consists of various tokens. A token is the smallest unit of the program which is used to build the blocks of Swift programs. They can be either a keyword, an identifier, a constant, a string literal, or a symbol.
Example
Swift program to demonstrate the use of tokens. Here the program contains 10 tokens such as import, Foundation, var, myString, etc.
import Foundation var myString = 34 print(myString)
Output
34
Semicolons
In Swift, semicolons after each statement are optional. It is totally up to your choice whether you want or not to type a semicolon (;) after each statement in your code, the compiler does not complain about it.
However, if you are using multiple statements in the same line, then it is required to use a semicolon as a delimiter, otherwise, the compiler will raise a syntax error.
Example
Swift program to demonstrate the use of semicolons in a single line.
// Separating multiple statements using semicolon var myString = "Hello, World!"; print(myString)
Output
Hello, World!
Identifiers
A Swift identifier is a name used to identify a variable, function, or any other user-defined item. An identifier name must start with the alphabet A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).
Swift does not allow special characters such as @, $, and % within identifiers. Swift is a case-sensitive programming language, so Manpower and manpower are two different identifiers in Swift.
Example
Following are some valid identifiers in Swift −
Azad zara abc move_name a_123 myname50 _temp j a23b9 retVal
Keywords
Keywords are the special pre-defined words available in Swift that have some special meaning and functionality. They are also known as reserved words. These reserved words may not be used as constants, variables or any other identifier names unless they're escaped with backticks(`).
For example, class is not a valid identifier, but `class` is valid. They are commonly designed to define the structure and behaviour of the programs. Swift supports the following keywords −
Keywords used in declarations
The following are Keywords used in declarations
Class | deinit | Enum | extension |
Func | import | Init | internal |
Let | operator | private | protocol |
public | static | struct | subscript |
typealias | var |
Keywords used in statements
The following are Keywords used in statements
break | case | continue | default |
do | else | fallthrough | for |
if | in | return | switch |
where | while |
Keywords used in expressions and types
The following are Keywords used in expressions and types
as | dynamicType | false | is |
nil | self | Self | super |
true | _COLUMN_ | _FILE_ | _FUNCTION_ |
_LINE_ |
Keywords used in particular contexts
The following are Keywords used in particular contexts
associativity | convenience | dynamic | didSet |
final | get | infix | inout |
lazy | left | mutating | none |
nonmutating | optional | override | postfix |
precedence | prefix | Protocol | required |
right | set | Type | unowned |
weak | willSet |
Whitespaces
Whitespace is the term used in Swift to describe blanks, tabs, newline characters, and comments. Whitespaces separate one part of a statement from another and enable the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
var age
There must be at least one whitespace character (usually a space) between var and age for the compiler to be able to distinguish them. On the other hand, in the following statement:
//Get the total fruits int fruit = apples + oranges
No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some for better readability.
Space on both sides of an operator should be equal, for example −
int fruit= apples +oranges //is a wrong statement int fruit = apples + oranges //is a Correct statement
Literals
A literal is the source code representation of a value of an integer, floating-point number, or string type. Or we can say that literals are the actual values that are directly written in the source code. Swift supports integer literals, floating-point literals, String literals, boolean literals, etc.
Example
Following is the examples of literals −
92 // Integer literal 4.24159 // Floating-point literal "Hello, World!" // String literal
Printing in Swift
In Swift, you can print anything to the console using the print() function. It is the most useful function in Swift language. It can also print files, functions and line numbers.
Syntax
Following is the syntax of the print() function −
func print(_element: Any…, Sep: String = “ “, Terminator: String = “\n”)
Parameters
This function takes only three parameters and they are optional −
Element − It is the element that we want to print as output in the console. It can be zero or more.
Sep − It represents a string that will be displayed between each element. By default, it takes a single space.
Terminator − It represents a string that will print after all the elements. By default, its value is a newline. We can give our custom separators and terminators according to our requirements.
Example
Swift program to demonstrate how to print text using print() function.
import Foundation // Printing text print("Learn Swift!") // Printing variables var x = 10 var y = 23 print("[\(x) and \(y)]") // Printing text with terminator print("Swift, Programming Language", terminator: "*") print("Swift Programming Language")
Output
Learn Swift! [10 and 23] Swift, Programming Language*Swift Programming Language