Swift — Syntax
Variables and constants
// let: constant (immutable)
let name = "Alice"
let age = 30
// var: variable (mutable)
var count = 0
count += 1
// Type annotation
let pi: Double = 3.14
var isActive: Bool = true
Type inference
let x = 42 // Int
let y = 3.14 // Double
let s = "hello" // String
let b = true // Bool
// Explicit type when needed
let price: Float = 9.99
String interpolation
let name = "Alice"
let age = 30
print("Name: \(name), Age: \(age)")
print("Next year: \(age + 1)")
Functions
// Basic function
func add(a: Int, b: Int) -> Int {
return a + b
}
// Single expression
func multiply(a: Int, b: Int) -> Int {
a * b
}
// Default parameters
func greet(name: String, greeting: String = "Hello") {
print("\(greeting), \(name)!")
}
// Named arguments
greet(name: "Alice")
greet(name: "Bob", greeting: "Hi")
Control flow
// if/else
let x = 10
if x > 5 {
print("big")
} else {
print("small")
}
// switch
let day = "Monday"
switch day {
case "Monday":
print("Start of week")
case "Friday":
print("Almost weekend")
case "Saturday", "Sunday":
print("Weekend!")
default:
print("Midweek")
}
// for loop
for i in 1...5 {
print(i)
}
// while
var y = 0
while y < 5 {
y += 1
}
Optionals
var name: String? = nil
// Safe unwrapping
if let name = name {
print(name)
} else {
print("No name")
}
// Guard
func process(name: String?) {
guard let name = name else {
print("No name")
return
}
print("Processing: \(name)")
}
// Nil coalescing
let display = name ?? "Unknown"
Collections
// Array
let nums = [1, 2, 3, 4, 5]
var mutable = [1, 2, 3]
mutable.append(4)
// Dictionary
let ages = ["Alice": 30, "Bob": 25]
// Set
let set: Set = [1, 2, 3, 2, 1] // [1, 2, 3]
Mini Practice
Write Swift code that:
- Uses
letandvarwith type inference - Creates a function with default parameters
- Uses optionals with
if let - Demonstrates a
switchstatement
Up Next
In the next lesson, you'll learn about Variables — declarations and types in Swift.
Related Topics
Frequently Asked Questions about Syntax
What is Syntax in Swift?
Syntax is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Syntax?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Syntax.
Why is Syntax important in Swift?
Syntax is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.