Lesson 2Swift Basics

Variables & Constants

Storing Data

In Swift, we store data using variables (can change) and constants (cannot change).

Variables (var)

Use var when the value might change later:

  • Game scores that increase
  • User's current location
  • Counter values

Constants (let)

Use let when the value will never change:

  • User's name (once set)
  • Mathematical constants like pi
  • Configuration values

Why Use Constants?

  • Safer - Prevents accidental changes
  • Faster - Swift can optimize your code
  • Clearer - Shows your intentions to others

Tip: Swift recommends using let by default!

main.swift
// Variables - values can change
var score = 0
score = 10
score = score + 5
print("Score: \(score)") // Score: 15

// Constants - values cannot change
let playerName = "Alex"
let maxLives = 3
// playerName = "Sam" // Error! Can't change a constant

// Type inference
var message = "Hello"  // Swift knows it's a String
var number = 42        // Swift knows it's an Int

// Explicit types
var greeting: String = "Hi there"
var age: Int = 12

// Multiple declarations
var x = 0, y = 0, z = 0
let a = 1, b = 2, c = 3

print("\(playerName) has \(maxLives) lives")

Try It Yourself!

Create a variable for your age (it changes each year) and a constant for your name (stays the same). Print them both!