Swift Variables and Constants

Store values with let and var, understand Swift's basic types, use type inference and annotations, and convert between types safely.

Lesson 2 of 43Beginner18 min read

Programs need to remember things: a player's name, the number of items in a basket, whether a switch is on. A variable is a named place to keep a value so you can use it later.

Swift has two keywords for this. let creates a constant, a value that can't change once it's set. var creates a variable that can. Swift strongly encourages let: Xcode even warns you when a var is never changed, because constants make code safer and easier to reason about.

Every value in Swift has a type, such as a whole number, a decimal or some text. Usually Swift works the type out for you from the value, which is called type inference. In this lesson you'll create constants and variables, meet the basic types, write types explicitly when it helps, convert between types and group values in tuples.

let and var

Swift
let name = "Ada"        // constant: can't change
var score = 0           // variable: can change
score = 10
score += 5
  • let values must be set once and never reassigned. name = "Grace" is a compile error: "cannot assign to value: 'name' is a 'let' constant".
  • var values can be changed as often as you like, but always to a value of the same type.
  • Use let by default, and switch to var only when the value really needs to change.

Types and type inference

TypeHoldsExample
IntWhole numbers42
DoubleDecimal numbers3.75
Booltrue or falsetrue
StringText"Swift"
CharacterA single character"S" (with a type annotation)

Swift infers the type from the value, so let age = 30 is an Int and let price = 9.99 is a Double. Add a type annotation with a colon when you want to be explicit, or when there's no value yet: var total: Double = 0 makes the 0 a Double, and let initial: Character = "A" makes a Character instead of a String.

Naming rules

  • Names can include letters, digits and underscores, and even emoji, but can't start with a digit or contain spaces.
  • Use lowerCamelCase: firstName, totalPrice, isLoggedIn.
  • Names are case-sensitive: score and Score are different.
  • Booleans read best as questions: isMember, hasTicket, canEdit.

Clear names matter more than short ones. let secondsPerMinute = 60 explains itself, while let s = 60 makes readers guess.

Converting types, and tuples

Swift never converts types automatically, not even Int to Double, which prevents subtle bugs. Convert explicitly:

Swift
let count = 3
let price = 2.5
let total = Double(count) * price      // 7.5
let whole = Int(9.99)                  // 9, decimals dropped
let text = String(count)               // "3"
let number = Int("42")                 // Optional(42): might fail

Turning text into a number might fail, so Int("42") returns an optional that you unwrap safely, as the optionals lesson explains.

A tuple groups a few values together: let point = (x: 3, y: 4), then point.x. Tuples are handy for returning two values from a function.

Declaring a constant now and setting it later

A let doesn't have to get its value on the same line. You can declare it with a type and assign it exactly once later, which is useful when the value depends on a decision:

Swift
let isMember = true
let message: String
if isMember {
    message = "Welcome back"
} else {
    message = "Sign up today"
}
print(message)       // Welcome back

The compiler checks every path. If one branch forgets to assign message, or tries to assign it twice, the code won't compile, and reading message before it has a value is also an error. This lets you keep a value constant even when working it out takes a few lines.

Several values on one line, and swapping

You can declare more than one variable in a single statement, separated by commas, and you can pull a tuple apart into separate names:

Swift
var a = 1, b = 2
let (x, y) = (3, 4)          // x is 3, y is 4
let (width, _) = (5, 6)      // _ ignores the second value
(a, b) = (b, a)              // swap: a is 2, b is 1

Pulling a tuple apart like this is called destructuring. The underscore _ means "I don't need this value", and you'll see it again in loops and functions. Swapping with a tuple needs no temporary variable, because Swift reads both values on the right before assigning either one.

Swift Variables Syntax

Constants and variables

let name = "Ada"               // constant, inferred String
var score: Int = 0             // variable, explicit type
score += 10
let total = Double(score) * 1.5
let text = String(score)
let maybe = Int("12")          // Int? (optional)
let point = (x: 1, y: 2)
point.x

Swift Variables Summary

  • let creates a constant; var creates a variable. Prefer let.
  • Basic types: Int, Double, Bool, String and Character.
  • Swift infers types from values; annotate with : Type when needed.
  • Types never change and never convert automatically; use Double(), Int() and String().
  • Converting text to a number returns an optional because it can fail.

Swift Variables Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A small profile

Swift
let name = "Priya"
let age = 28
let height = 1.68
let isMember = true
var points = 120

points += 30
print(name, age + 1, height, isMember, points)
print(type(of: height))
Output
Priya 29 1.68 true 150
Double
Line-by-line explanation
  1. Lines 1 to 4Types are inferred: String, Int, Double and Bool.
  2. Line 5points will change, so it's a var.
  3. Line 7+= adds to the current value.
  4. Line 9type(of:) shows the inferred type.
Example 2

Converting between types

Swift
let items = 3
let itemPrice = 12.5
let total = Double(items) * itemPrice
print("Total:", total)

let typed = "25"
if let years = Int(typed) {
    print("Months:", years * 12)
}
print(Int(9.99), String(items) + " items")
Output
Total: 37.5
Months: 300
9 3 items
Line-by-line explanation
  1. Line 3Double(items) converts the Int, so it can be multiplied by a Double.
  2. Lines 7 to 9Int(typed) might fail, so if let only runs the block when it succeeds.
  3. Line 10Converting to Int drops the decimals; String() turns a number into text.
Example 3

Tuples

Swift
let product = (name: "Mug", price: 8.5, stock: 12)
print(product.name, product.price)

let (name, price, _) = product
print("\(name) costs £\(price)")

let size = (width: 1920, height: 1080)
print("Pixels:", size.width * size.height)
Output
Mug 8.5
Mug costs £8.5
Pixels: 2073600
Line-by-line explanation
  1. Line 1A tuple with named parts.
  2. Line 4Destructuring copies the parts into separate constants; _ ignores one.
  3. Line 5\( ) inside a string inserts a value, which the strings lesson explains.

Common Swift Variables Mistakes

Changing a constant

Don't
let lives = 3
lives = 2              // error: cannot assign to value: 'lives' is a 'let' constant
Do
var lives = 3
lives = 2

Mixing Int and Double

Don't
let count = 3
let total = count * 2.5     // error: binary operator '*' cannot be applied to 'Int' and 'Double'
Do
let total = Double(count) * 2.5

Changing a variable's type

Don't
var score = 10
score = "ten"               // error: cannot assign value of type 'String' to type 'Int'
Do
var score = 10
score = 20

Swift Variables in Real Projects

Variables in apps

In a SwiftUI app, constants hold fixed values like spacing and colours, while var properties hold the state that changes as people use the app: the text in a search field, whether a toggle is on, the items in a list. Swift's strict types mean mistakes like adding text to a number are caught while you type, long before an app reaches users.

Swift Variables FAQ

What is the difference between let and var in Swift?

let declares a constant that can be assigned once and never changed; var declares a variable that can be reassigned. Both have a fixed type. Use let unless the value genuinely changes, and Xcode will warn you when a var is never modified.

Does let make an array or dictionary unchangeable?

Yes. Arrays, dictionaries, sets and strings are value types in Swift, so a let array can't have items added, removed or replaced: let list = [1] followed by list.append(2) is a compile error. Declare it with var if you need to change its contents.

When should I write a type annotation in Swift?

Write one when there's no starting value, as in let message: String, or when the inferred type isn't the one you want, as in var total: Double = 0 or let grade: Character = "A". Otherwise let Swift infer the type, which keeps code short.

Why can't I add an Int and a Double in Swift?

Swift never converts number types silently, because hidden conversions can lose precision or hide bugs. Convert one side explicitly: Double(count) * price. Plain number literals are the exception, since 2.5 * 2 lets the literal 2 become a Double.

What does the underscore mean in let (x, _) = point?

The underscore is a placeholder for a value you don't need. In let (x, _) = (3, 4), only x is created and the 4 is thrown away. It avoids an unused-variable warning and tells readers the value was ignored on purpose.

Swift Variables Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the declaration so the value can never change.

 maxPlayers = 4
Predict the outputeasy

What type does Swift infer for let x = 4.0?

Predict the outputmedium

What does this print?

var a = 5
let b = a
a = 9
print(b)
Multiple choicemedium

Which line correctly multiplies an Int count by 2.5?

Multiple choicehard

What type does Int("abc") produce?

Swift Variables Quiz

5 questions to check what you learned.

  1. What's the difference between let and var?

    • let is for numbers, var for text
    • var is faster
    • There's none
    • let values can't change; var values can
  2. What does Int(9.99) return?

    • 9
    • 10
    • 9.99
    • nil
  3. Which naming style does Swift use for variables?

    • snake_case
    • lowerCamelCase
    • UPPERCASE
    • kebab-case
  4. How do you read the price from let item = (name: "Pen", price: 1.2)?

    • item.price
    • item["price"]
    • item(price)
    • item[1].price
  5. Why doesn't Swift convert Int to Double automatically?

    • It's a limitation that will be removed
    • Doubles aren't supported
    • Explicit conversions prevent hidden mistakes and loss of precision
    • Ints are always bigger