Swift — Variables
let and var
// let: immutable constant
let name = "Alice"
let age = 30
// var: mutable variable
var score = 95
score += 5
// Type annotation
let pi: Double = 3.14
var count: Int = 0
Optionals
var nickname: String? = "Ali"
nickname = nil
// Unwrapping
if let nick = nickname {
print(nick)
} else {
print("No nickname")
}
// Guard
func process(name: String?) {
guard let name = name else {
print("No name")
return
}
print("Processing: \(name)")
}
// Nil coalescing
let display = nickname ?? "Unknown"
// Optional chaining
let upper = nickname?.uppercased()
Type aliases
typealias UserDict = [String: Int]
let ages: UserDict = ["Alice": 30, "Bob": 25]
print(ages)
Tuple
let person = ("Alice", 30)
print(person.0, person.1)
// Named tuple
let (name2, age2) = ("Bob", 25)
print(name2, age2)
Constants and literals
let binary = 0b1010 // 10
let octal = 0o17 // 15
let hex = 0xFF // 255
let scientific = 1.25e2 // 125.0
Best practices
- Prefer
letovervar - Use optionals carefully
- Use
guardfor early returns - Use type aliases for clarity
Mini Practice
Write Swift code that:
- Uses
letandvarwith type inference - Demonstrates optional unwrapping with
if let - Uses
guardfor early return - Creates a type alias
Up Next
In the next lesson, you'll learn about Data Types — the full type system in Swift.
Related Topics
Frequently Asked Questions about Variables
What is Variables in Swift?
Variables 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 Variables?
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 Variables.
Why is Variables important in Swift?
Variables is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.