Swift Variables

Understanding variables and data storage in Swift

📦 What are Variables?

Variables in Swift store data that can change during program execution. Use the 'var' keyword to create variables that can be modified later in your code.


// Creating and using variables
var playerName = "Alice"
var score = 100
print("\(playerName) has \(score) points")
                                    

Output:

Alice has 100 points

Variable Characteristics

🔄

Mutable

Values can be changed

var count = 5
count = 10 // Allowed
🏷️

Named Storage

Variables have descriptive names

var userName = "John"
var userAge = 25
🎯

Type Safe

Each variable has a specific type

var name: String = "Alice"
var age: Int = 30
🔍

Type Inference

Swift can guess the type

var message = "Hello" // String
var number = 42 // Int

🔹 Declaring Variables

There are several ways to declare variables in Swift:

// Method 1: Let Swift infer the type
var name = "John Doe"        // Swift knows this is String
var age = 25                 // Swift knows this is Int
var height = 5.9             // Swift knows this is Double

// Method 2: Explicitly specify the type
var city: String = "New York"
var population: Int = 8000000
var temperature: Double = 72.5

// Method 3: Declare first, assign later
var country: String
country = "United States"

print("Name: \(name)")
print("Age: \(age)")
print("Height: \(height) feet")
print("City: \(city)")
print("Population: \(population)")
print("Temperature: \(temperature)°F")
print("Country: \(country)")

Output:

Name: John Doe

Age: 25

Height: 5.9 feet

City: New York

Population: 8000000

Temperature: 72.5°F

Country: United States

🔹 Modifying Variables

Variables can be changed after they're created:

// Initial values
var playerScore = 0
var playerLevel = 1
var playerName = "Beginner"

print("Starting stats:")
print("Name: \(playerName)")
print("Level: \(playerLevel)")
print("Score: \(playerScore)")

// Modify the variables
playerScore = 150
playerLevel = 2
playerName = "Novice"

print("\nAfter playing:")
print("Name: \(playerName)")
print("Level: \(playerLevel)")
print("Score: \(playerScore)")

// Increment score
playerScore += 50  // Same as: playerScore = playerScore + 50
print("\nBonus points added!")
print("New Score: \(playerScore)")

Output:

Starting stats:

Name: Beginner

Level: 1

Score: 0

After playing:

Name: Novice

Level: 2

Score: 150

Bonus points added!

New Score: 200

🔹 Variable Types

Swift has many built-in variable types:

// String variables
var firstName = "John"
var lastName = "Smith"
var fullName = firstName + " " + lastName

// Numeric variables
var wholeNumber: Int = 42
var decimalNumber: Double = 3.14159
var floatNumber: Float = 2.5

// Boolean variables
var isStudent = true
var hasLicense = false

// Character variables
var grade: Character = "A"
var symbol: Character = "★"

print("Full Name: \(fullName)")
print("Whole Number: \(wholeNumber)")
print("Decimal: \(decimalNumber)")
print("Float: \(floatNumber)")
print("Is Student: \(isStudent)")
print("Has License: \(hasLicense)")
print("Grade: \(grade)")
print("Symbol: \(symbol)")

Output:

Full Name: John Smith

Whole Number: 42

Decimal: 3.14159

Float: 2.5

Is Student: true

Has License: false

Grade: A

Symbol: ★

🔹 Variable Naming Rules

Follow these rules when naming variables:

✅ Valid Variable Names:

  • Start with letter or underscore: name , _count
  • Use camelCase: firstName , userAge
  • Include numbers (not at start): player1 , level2
  • Use descriptive names: totalScore , isActive

❌ Invalid Variable Names:

  • Start with number: 1name
  • Use spaces: user name
  • Use reserved words: var , let , if
  • Special characters: user@name , total$
// Good variable names
var userName = "Alice"
var totalScore = 1500
var isGameActive = true
var player1Name = "Bob"
var _privateData = "secret"

// Better to use descriptive names
var currentTemperature = 75.5
var numberOfStudents = 30
var hasCompletedLevel = false

print("User: \(userName)")
print("Score: \(totalScore)")
print("Game Active: \(isGameActive)")
print("Temperature: \(currentTemperature)°F")
print("Students: \(numberOfStudents)")
print("Level Complete: \(hasCompletedLevel)")

Output:

User: Alice

Score: 1500

Game Active: true

Temperature: 75.5°F

Students: 30

Level Complete: false

🧠 Test Your Knowledge

Which keyword is used to declare a variable in Swift?