First Program in Swift
When starting with Swift, the first step is understanding how to write a simple program. In this section, we'll walk you through creating your first Swift program while exploring the fundamental building blocks of the language—variables, constants, literals, and comments
Your First Swift Program
Let's start by writing a simple "Hello, World!" program. Open your Swift environment (Xcode, Playground, or any Swift compiler) and type the following:
print ( "Hello World!" )
Output
Hello World!
This one line of code introduces some key concepts about Swift syntax. Now, let's build on this and dive deeper into variables, constants, literals, and comments.
Understanding Variables in Swift
In Swift, a variable is a named storage location that holds data. Each variable has a specific type, defining the values it can store and the operations applicable to it.
Key Characteristics of Swift Variables
- ✔ Statically Typed – A variable’s type is fixed at declaration and cannot change.
- ✔ Mutable – Its value can be modified after declaration.
- ✔ Declared with var – The var keyword is used for variable declarations.
Declaring Variables in Swift
Syntax
var variableName = value
Example
Declaring a Single Variable.
import
Foundation
// Declaring variable
var
num
= 100
print
( "Variable:" num)
Output
Variable: 100
Declaring Multiple Variables in One Line
Swift allows multiple variable declarations in a single line, with values separated by commas.
Syntax
var variableA = value, variableB = value, varaibleC = value
Example
import
Foundation
// Declaring multiple variables
var
variableA
= 50,
variableB
=
"swift",
variableC
=
5.9
print("Variable 1:" variableA)
print("Variable 2:" variableB)
print("Variable 3:" variableC)
Output
Variable 1: 50
Variable 2: swift
Variable 3: 5.9
Key Takeaways
- Swift variables are statically typed but mutable.
- Declared using var before use.
- Multiple variables can be declared in one line.
Type Annotations in Swift
In Swift, type annotation explicitly defines the type of value a variable will hold at the time of declaration. It is useful for clarity but not always required because Swift infers types from assigned values.
- Ensures Type Safety – Helps prevent unintended type assignments.
- Improves Code Readability – Clearly states what type a variable holds.
- Required for Empty Variable Declarations – When a variable is declared without an initial value.
Syntax of Type Annotation
Following is the syntax of type annotations −
var variableName : Type = value
Example
Declaring a Variable with Type Annotation
import
Foundation
// Declaring a variable with a type annotation
var
myValue :
String
=
"Hello World"
print(
"Variable:",
myValue
)
Output
Variable: Hello World
Declaring Multiple Variables with the Same Type
Swift allows multiple variable declarations of the same type in a single line, separated by commas.
Syntax
Following is the syntax of multiple variables −
var variableA, variableB, varaibleC : Type
Example
Declaring Multiple Variables with Type Annotation
import
Foundation
// Declaring multiple variables in single-type annotation
var
myValue1,
myValue2,
myValue3 :
Int
// Assigning values
myValue1 = 50
myValue2 = 60
myValue3 = 70
print (
"Variable Value 1:", myValue1 )
print (
"Variable Value 2:", myValue2 )
print (
"Variable Value 3:", myValue3 )
Output
Variable Value 1: 50
Variable Value 2: 60
Variable Value 3: 70
Key Takeaways
- Swift infers types automatically but annotations improve clarity.
- Use type annotations when declaring variables without an initial value.
- Multiple variables of the same type can be declared in one line.
Naming Variables in Swift
Proper variable naming is essential for writing readable, maintainable, and error-free code. Swift enforces strict rules when naming variables to ensure clarity and consistency.
Swift Variable Naming Rules
-
✅ Can Contain Unicode Characters – Swift supports
non-English characters:
var 你好 = "你好世界" // Allowed
-
✅ Cannot Contain Special Symbols or Spaces – Variable
names cannot include:
• Mathematical symbols (+, -, *, /)
• Arrows (→, ←)
• Private-use Unicode scalar values
• Line and box drawing characters -
✅ Must Start with a Letter or Underscore (_) – Cannot
begin with a number:
var myValue = 34 // ✅ Allowed
var _hiddenVar = 10 // ✅ Allowed
var 1stValue = 100 // ❌ Not Allowed
-
✅ Swift is Case-Sensitive –
value
andValue
are different variables:
var value = 10
var Value = 20
print(value, Value) // 10 20
-
✅ Cannot Use Reserved Keywords Directly – Use backticks
for reserved words:
var `break` = "Swift" // ✅ Allowed
print(`break`) // Swift
-
✅ Cannot Re-declare a Variable with the Same Name – Even
if the type is different:
var age = 25
var age = "Twenty-five" // ❌ Error: Cannot redeclare variable
-
✅ Cannot Convert a Variable into a Constant (let) – Once
declared, it must remain the same type:
var name = "Swift"
// let name = 10 // ❌ Error: Cannot change variable to constant
Printing Variables in Swift
To print variables, use the print() function. Swift supports string interpolation using backslash \() syntax.
Example
Printing Variables
import
Foundation
// Declaring variables
var
name
=
"swift"
var
version
=
6.0
//version of swift
print
(
"version of \(name) is at version
\(version) "
)
Output
version of swift is at version 6.0
Understanding Constants in Swift
A constant in Swift is a fixed value that cannot be modified after it is assigned. Constants are useful when you need to store values that never change during the program's execution.
Declaring Constants in Swift
Constants are declared using the let keyword.
Syntax
let constantName = value
Example
Declaring a Constant.
import
Foundation
// Declaring constant
let
const
= 10
print ("Constant:" ,
const)
Output
Constant: 10
Constants Cannot Be Changed
Once a constant is declared, trying to modify it will result in an
error.
Example
Attempting to Modify a Constant
import
Foundation
// Declaring constant
let
constA
= 42
print ("Constant:",
constA)
// Assigning value to a constant
constA = 43
print ("Constant:",
constA)
Output
ERROR!
/tmp/iloPscGF01/main.swift:8:1: error: cannot assign to value:
'constA' is a 'let' constant
constA = 43
^~~~~~
/tmp/iloPscGF01/main.swift:4:1: note: change 'let' to 'var' to
make it mutable
let constA = 42
^~~
var
Declaring Multiple Constants
You can declare multiple constants in a single line, separating them with commas.
Syntax
let constantA = value, constantB = value, constantC = value
Example
Multiple Constants in One Line
import
Foundation
// Declaring multiple constant
var
constA
= 55,
constB
=
99,
constC
=
33
print("Constant 1:" , constA)
print("Constant 2:" , constB)
print("Constant 3:" , constC)
Output
Constant 1: 55
Constant 2: 99
Constant 3: 33
Type Annotations with Constants in Swift
Type annotations allow you to explicitly define the type of a constant. This helps improve code clarity and ensures that a constant holds values of a specific type.
Declaring a Constant with Type Annotation
Syntax
let constantA: Type
Example
Using Type Annotation with Constants
import
Foundation
// Declaring multiple variables in single-type annotation
let
myValue1:
Int
= 50
print (
"Variable Value 1:", myValue1 )
Output
Variable Value 1: 50
Example: Multiple Constants in One Line
import
Foundation
// Declaring multiple constants with the same type
let
myValue1, myValue2, myValue3: Int
// Assigning values
myValue1 =
23
myValue2 =
22
myValue3 =
11
print("Constant 1:", myValue1)
print("Constant 2:", myValue2)
print("Constant 3:", myValue3)
Output
Constant 1: 23
Constant 2: 22
Constant 3: 11
Naming Constants in Swift
When naming a constant, you must follow Swift’s naming rules to avoid errors.
- ✔️ Can contain letters, digits, and underscores (_)
-
✔️ Can contain Unicode characters (
let 你好 = "你好世界"
) - ✔️ Must begin with a letter or underscore (_)
-
✔️ Uppercase and lowercase letters are distinct (
let value ≠ let Value
) - ✔️ If using a reserved keyword, enclose it in backticks (` `):
let `var` = "hello" // ✅ Allowed print(`var`) // Output: hello
-
❌ Cannot start with a number (
let 1number = 10
) -
❌ Cannot contain spaces or special symbols (
let my value = 42
) - ❌ Cannot redeclare a constant with the same name
-
❌ Cannot change a constant into a variable (
var
)
Printing Constants in Swift
You can print constants using print() or use string interpolation for better formatting.
Example
import
Foundation
// Declaring constant
let
name
=
"Swift"
let
version
=
5.9
// Using string interpolation
print
(
"Value of The programming language\(name)
is at version
\(version) million"
)
Output
The programming language Swift is at version 5.9.
Understanding Swift - Literals
What are Literals?
Literals are fixed values written directly in Swift source code. They represent numbers, characters, strings, or Boolean values.
For example:
- 34 → Integer literals
- 23.45 → Floating-point literals
- "Hello" → String literals
- true → Boolean literals
Literals cannot be modified, but you can store them in variables or constants to perform operations.
Types of Swift Literals
1. Integer Literals
Used to represent whole numbers. You can specify both positive and negative values.
let positiveNumber = 10
let negativeNumber = -10
Integer Literal Types:
No | Type | Prefix | Example |
---|---|---|---|
1 | Decimal (Base 10) | None | 34 |
2 | Binary (Base 2) | 0b | 0b1011 |
3 | Octal (Base 8) | 0o | 0o53 |
4 | Hexadecimal (Base 16) | 0x | 0xFF |
Example
Integer Literals in Swift
let
decimalNumber
=
90
let
binaryNumber
= 0b1011
let
octalNumber
= 0o53
let hexNumber
= 0xFF
print(decimalNumber)
print(binaryNumber)
print(octalNumber)
print(hexNumber)
Output
90
11
43
255
Swift - Floating-Point Literals
A floating-point literal represents a number with a fractional component (decimal or exponential form).
For example:
- 34.567 (Decimal floating-point)
- 1.243e4 (Exponential notation)
- 0xC.3p0 (Hexadecimal floating-point)
Types of Floating-Point Literals in Swift
Type | Example | Explanation |
---|---|---|
Decimal Floating-Point | 12.1875 | Normal decimal numbers |
Exponential Notation | 1.243e4 | Equivalent to 1.243 × 10^4 = 12430 |
Hexadecimal Floating-Point | 0xC.3p0 | Uses base 16, p represents exponent |
Example: Floating-Point Literals in Swift
import
Foundation
// Decimal floating-point literal
let
num1
=
89.3
print("Decimal Float: \(num1) ")
// Exponential notation floating-point literal
let
num2
=
3.5e3
print("Binary Float: \(num2) ")
// Hexadecimal floating-point literal
let
num3
=
0x3p-3
print("Hexadecimal Float: \(num3) ")
Output
Decimal Float: .89.3
Exponential Float: 3500.0
Hexadecimal Float:0.375
Swift - String Literals
A string literal is a sequence of characters enclosed in double quotes ("...").
Types of String Literals in Swift:
-
✔ Single-line string →
"Hello, Swift!"
-
✔ Multi-line string →
"""This is a multi-line string"""
-
✔ String with escape sequences →
"Line break\nTab\tQuote: \" "
Single-Line String Literals
Used for regular one-line text enclosed in double quotes ("...").
Multi-Line String Literals
Use triple double-quotes ("""...""") to span multiple lines.
import
Foundation
// Single-line string
let
singleLineString
=
"Hello, Swift!"
print("Single-line string:
\(singleLineString)")
// Multi-line string
let
multiLineString
= """
This is a multi-line string
"""
print("Multi-line string:
\(multiLineString)")
Output
Single-line string: Hello, Swift!
Multi-line string: This is a multi-line string
Escape Sequences in Strings
Escape sequences allow special characters inside string literals.
Escape Sequence | Description | Example Output |
---|---|---|
\n | Newline | Hello\nWorld → Hello World |
\t | Horizontal Tab | Name:\tSwift → Name: Swift |
\\ | Backslash (\) | C:\\Users\\Documents |
\" | Double Quote (") | "This is a \"quote\"." |
\' | Single Quote (') | 'Swift\'s power' |
\0 | Null Character | Not commonly used |
\u{1F60A} | Unicode Character (Emoji) | "Smile: \u{1F60A}" 😊 |
Example: Using Escape Sequences in a String
import
Foundation
// String with special characters and escape sequences
let
specialChars
=
"Swift:\n\t\"Fast Safe\"\n\t\\Powerful\\"
print(specialChars)
Output
Swift:
"Fast & Safe"
\Powerful\
Swift - Boolean
Boolean literals represent true or false values in Swift. They are mainly used for conditional statements and logic operations.
Boolean Values in Swift
There are only two Boolean literals in Swift:
- true
- false
let
isSwiftAwesome
= true
let
isJavaBetter
= false
print("Swift is awesome:
\(isSwiftAwesome)")
print("Java is better than Swift:
\(isJavaBetter)")
Output
Swift is awesome: true
Java is better than Swift: false
Comments are ignored by the compiler and used for documentation and code explanation.
Swift Supports Three Types of Comments:
//
)/* ... */
)/* /* ... */ */
)Single Line Comment
A single-line comment is used to add only one-liner text in the code. A single-line comment begins with double forward slashes (//). The compiler or interpreter always ignores them and does not affect the execution of the program.
Multi-Line Comment in Swift
Multi-line comments are used to display multiple lines of non-executable text in the program to explain the working to the specific line of code or to add warnings, notes, etc. by the developers. Like other programming languages, in Swift, the multi-line comments begin with a forward slash followed by an asterisk(/*) and end with an asterisk followed by the forward-slash (*/).
Nested Multi-Line Comment in Swift
Starting from Swift 4 a new feature is also included in the multi-line comment that is nested multi-line comment. Now you are allowed to nest or add a multi-line comment inside another multi-line comment. It can easily comment out many blocks, even if the block contains multi-line comments.
Example:
// This is a single-line comment
/* This is a multi-line comment
It spans multiple lines */
/* Outer multi-line comment
/* Nested multi-line comment */
Back to the outer comment */
import Foundation
// Function to add two numbers
func addNumbers(a: Int, b: Int) -> Int {
return a + b
}
let result = addNumbers(a: 5, b: 10)
print("Sum: \(result)")
Output
Sum: 15