Swift Syntax

Swift Introduction

✨ Swift Syntax (Basics Explained Clearly)

Swift syntax is clean, readable, and beginner-friendly. Let’s understand it step by step with simple examples.

 1. Swift Program Structure

A basic Swift program looks like this:

print("Hello, Swift!")

✔ No main() function
✔ No semicolons required
✔ Code runs top-to-bottom


 2. Comments in Swift

Comments are ignored by the compiler.

Single-line comment

// This is a comment

Multi-line comment

/*
This is a
multi-line comment
*/


 3. Variables & Constants

Variable (var) – value can change

var age = 25
age = 26

Constant (let) – value cannot change

let pi = 3.14
// pi = 3.15 ❌ error

✅ Swift prefers constants (let) for safety


 4. Data Types

Swift can automatically detect types, but you can also define them.

let name: String = "Swift"
let year: Int = 2024
let price: Double = 99.99
let isActive: Bool = true

 5. Type Inference

Swift automatically understands data types:

let city = "Delhi" // String
let count = 10 // Int
let rating = 4.5 // Double

 6. String Interpolation

Insert variables inside strings easily:

let language = "Swift"
print("I am learning \(language)")

Output:

I am learning Swift

 7. Operators

Arithmetic Operators

let sum = 10 + 5
let diff = 10 - 5
let mul = 10 * 5
let div = 10 / 5

Comparison Operators

10 == 10 // true
10 != 5 // true
10 > 5 // true

 8. If–Else Condition

let marks = 75

if marks >= 60 {
print(“Pass”)
} else {
print(“Fail”)
}

✔ Curly braces {} are mandatory


 9. Switch Statement

More powerful than other languages:

let grade = "A"

switch grade {
case “A”:
print(“Excellent”)
case “B”:
print(“Good”)
default:
print(“Average”)
}

✔ No break needed
✔ Must be exhaustive


 10. Loops

For Loop

for i in 1...5 {
print(i)
}

While Loop

var x = 1
while x <= 3 {
print(x)
x += 1
}

 11. Functions

func greet(name: String) {
print("Hello, \(name)")
}
greet(name: “Sanjit”)


 12. Semicolons?

Optional (not recommended):

let a = 10; let b = 20

 Swift Syntax Highlights

✔ Clean & readable
✔ Strong type safety
✔ No boilerplate
✔ Beginner-friendly
✔ Modern features

You may also like...