Swift Basic Syntax
In this article, we will explore about various basic syntax in swift.
Swift Printing and String interpolation
In Swift, print() function is used to print a value and \() for string interpolation as following –
|
1 2 3 |
var name = "John" var age = 25 print("I am \(name). I am \(age) years old") |
Swift Comments
Swift Comments are a set of statements that are not executed by the Swift compiler and interpreter. The use of comments makes it easy for humans to understand the source code.
Swift Single-line Comments:-
A ‘//’ (double forward slash) is used to specify a single line comment, which extends up to the newline character.
|
1 2 |
// It prints Hello, World! print("Hello, World!") |
Output:-
|
1 |
Hello World! |
Swift Multi-line Comments:-
If you want to comment multiple lines then you can do it using /* and */, everything in between from /* to */ is ignored by the compiler-
|
1 2 3 |
/* It prints Hello World! */ print("Hello, World!") |
Output:-
|
1 |
Hello World! |
Semicolons In Swift
In Swift it is not mandatory to put a semicolon (;) at the end of each statement, it is optional in swift.But, if you are typing multiple statements in single line, then it is necessary to use a semicolon as a delimiter, otherwise the compiler will raise a syntax error.
Example 1:-
|
1 |
var str = "Hello, World!" |
OR
|
1 |
var str = "Hello, World!"; |
Here, both the statements are valid swift statement.
Example 2:-
|
1 |
<span class="kwd">var</span><span class="pln"> str</span><span class="pun">=</span> <span class="str">"Hello, World!"</span><span class="pun">;</span> <span class="kwd">print</span><span class="pun">(</span><span class="pln">str</span><span class="pun">)</span> |
Swift Whitespaces
In Swift, Whitespace is used to indicate blanks, tabs, newline characters, comments. Whitespace are also useful separate one part of any statement from another.
Example:-
|
1 |
var str = "Hello, World!"; |



