Module 2: Variables & Data Types in Swift
In this module, we will dive into how Swift handles variables, constants, and the essential data types you’ll use in almost every Swift program. Understanding these basics will set a strong foundation for writing clean and efficient Swift code.
🔰 What are Variables and Constants?
In Swift:
var
declares a variable that can be changed after being set.let
declares a constant that cannot be changed once assigned.
Example:
var name = "Alice" let pi = 3.14159
If you try to change a constant, Swift will show an error:
pi = 3.14 // ❌ Error: Cannot assign to value: 'pi' is a 'let' constant
🧠 Type Inference vs Type Annotation
Swift can automatically infer the type from the assigned value, but you can also explicitly specify it.
var age = 25 // Type Inference: Int var message: String = "Hello" // Explicit Type Annotation
💡 Swift Data Types
Common Swift data types include:
Type | Description | Example |
---|---|---|
Int |
Integer numbers | let age = 30 |
Double |
Decimal numbers | let price = 99.99 |
String |
Text | let name = "Swift" |
Bool |
Boolean true/false | let isActive = true |
Character |
A single character | let grade: Character = "A" |
🔤 String Interpolation
Embed variables inside strings easily:
let name = "John" print("Hello, \(name)") // Output: Hello, John
🎯 Type Safety & Type Conversion
Swift is type-safe, so it does not convert between types automatically. You must convert explicitly.
let age = 30 let ageString = String(age) // Convert Int to String
Converting from String
to Int
returns an Optional
, which you must safely unwrap:
let input = "100" if let number = Int(input) { print("Number is \(number)") } else { print("Invalid number") }
🧪 Playground: Sample Program
// variables.swift let siteName: String = "SwiftTutorial" var userCount: Int = 1000 var isOnline: Bool = true print("Welcome to \(siteName)!") print("Active users: \(userCount)") print("Server online: \(isOnline)")
Save the above as variables.swift
and run it:
swift variables.swift
⚙️ Constants vs Variables – When to Use?
Use let when… |
Use var when… |
---|---|
Value does not change after assignment | Value will change during program execution |
Ensures immutability and safety | Allows flexibility and updates |
✅ Practice Exercises
- Declare your name, age, and a boolean
isStudent
. - Print a sentence using all three variables.
- Convert an age from
String
toInt
safely. - Try to reassign a
let
constant and observe the error.
📝 Summary
In this module, you learned how to declare variables and constants, understood Swift’s type inference and type safety, explored basic data types, and practiced type conversion and string interpolation. These core concepts are essential for writing robust Swift programs. Next, we’ll explore control flow and decision-making in Swift.