Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 146 Β· Getting Started

Constants and Variables

Learn Swift constants and variables - let and var, type inference, annotations, naming rules, deferred initialization and shadowing, with real compiler errors.

A program is mostly about values: a price, a name, a list of scores. To work with a value you give it a name, and Swift offers two kinds of names. A constant, declared with let, is bound to a value once and can never be reassigned. A variable, declared with var, can be given new values as the program runs.

Swift is unusual in how strongly it nudges you toward constants. The standard advice, which the compiler even enforces with warnings, is: start with let, and change it to var only when you actually need to change the value. This lesson shows how, and then covers type inference, type annotations, naming, deferred initialization and shadowing.

let and var

Swift A constant and a variable

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

maximumAttempts never changes, so it is a let. attemptsUsed changes, so it is a var. The assignment attemptsUsed += 1 is shorthand for attemptsUsed = attemptsUsed + 1.

If you try to change a constant, the compiler stops you:

Swift Assigning to a let constant (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The real diagnostic is:

TEXT
main.swift:2:1: error: cannot assign to value: 'maximumAttempts' is a 'let' constant

with a note: change 'let' to 'var' to make it mutable. Notice what this gives you. When you read code and see let, you know that name means the same thing for its entire lifetime, which removes a whole category of "who changed this?" questions.

The opposite mistake, a var that nobody changes, produces a warning, not an error:

Swift A var that is never changed (warning)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler says warning: variable 'greeting' was never mutated; consider changing to 'let' constant. (It reports this for variables inside functions and other local scopes; a top-level var in main.swift is a global and is not checked.) The program still runs, but treat warnings as to-do items. In this course we fix every warning, and so should you.

Habit to build: write let by default. Change to var when the compiler tells you that you need it. Your code ends up with fewer moving parts.

Type inference

You did not write the types in the example above. Swift looked at the value on the right of = and inferred the type: 3 is an Int, "Hello" is a String, 2.5 is a Double, true is a Bool. Inference happens at compile time; the variable has a single, fixed type for its whole life.

Swift Asking Swift what it inferred

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The function type(of:) returns the type of its argument; here it tells you Int, Double, String, Bool and Array<String>. Inference is not dynamic typing: once count is an Int, count = "x" is a compile error.

A literal such as 3.0 or 0.5 always defaults to Double, and an integer literal defaults to Int. When the context demands something else, the same literal adapts:

Swift
let ratio: Float = 0.5   // read-only: the literal becomes a Float
let small: UInt8 = 200   // the literal becomes a UInt8

Type annotations

Sometimes you need to state the type yourself. You write a colon and the type after the name. This is a type annotation.

Swift Annotations choose a different type

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Use an annotation in three situations: (1) the default type is not what you want (Double for the literal 5), (2) the compiler cannot infer enough, for example an empty array or dictionary, (3) you declare a name now and give it a value later, as label shows. In every other case, leave the annotation out. Writing let name: String = "Mina" is legal but noisy.

If the inference fails, the compiler asks for help. This example is ambiguous:

Swift Nothing to infer from (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is error: empty collection literal requires an explicit type. The cure is an annotation: let nothing: [String] = [].

You can declare several names of the same type on one line, with one annotation at the end: var x = 0, y = 0, z = 0 or var red, green, blue: Double. Use it sparingly; one declaration per line is easier to read.

Deferred initialization

A let does not have to be assigned where it is declared. You may declare it and assign it exactly once, as long as the compiler can prove that every path assigns it before it is read. This is handy when the value depends on a condition:

Swift Assigning a let in each branch

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each branch assigns advice once, and the compiler checks it. If you forget the else branch, you get error: constant 'advice' used before being initialized, because the compiler found a path where advice has no value. Compare this with the if expression you will learn in if and else, which lets you write let advice = if temperature > 30 { ... } else { ... }.

Naming rules and conventions

Names can contain letters, digits and underscores and cannot start with a digit. Swift names can use almost any Unicode character, so Ο€, ΠΏΡ€ΠΈΠ²Π΅Ρ‚ and ζ—₯本θͺž are legal, but be kind to your teammates. Reserved words such as let, class or func cannot be names unless wrapped in backticks, for example `class`. That works, but avoid it.

Conventions every Swift programmer follows:

  • Variables, constants and functions: lowerCamelCase (attemptsUsed, fetchUser).
  • Types and protocols: UpperCamelCase (BankAccount, Equatable).
  • Booleans read like statements: isEmpty, hasPrefix, canSubmit.
  • Be descriptive. elapsedSeconds is better than t or elapsedSecondsSinceTheProgramStarted.
  • Avoid abbreviations unless they are universal (url, id).

Swift's official API Design Guidelines stress clarity at the point of use: a name is read every time somebody uses it, but written once.

Shadowing

You may declare a new name inside an inner scope (for example inside a block or loop) that has the same name as an outer one. The inner name shadows the outer one for as long as the inner scope lasts.

Swift Shadowing in an inner scope

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The inner level is a different constant from the outer one; the outer stays 1. Shadowing is common with optionals, for example if let name = name, which creates a non-optional name that shadows the optional one (see Optionals).

You cannot, however, declare the same name twice in the same scope:

Swift Redeclaring in the same scope (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is error: invalid redeclaration of 'count', with a note pointing to the first declaration. Use a new name, or assign to a var.

Shadowing is useful but can confuse readers when a small inner scope hides an important outer value. If you find yourself unsure which level is meant, rename one of them.

Constants are not always immutable inside

There is a subtle point that bites beginners from other languages. let fixes the binding, and what that means depends on the type. For value types (structs, arrays, strings), a let also makes the contents unchangeable. For class instances, a let fixes the reference, but the object's own var properties can still be modified.

Swift let with a class versus a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

If box were declared with let, the assignment to box.size would fail. Value semantics and let together give you true immutability, which is another reason Swift favors structs (Structs, Value vs Reference).

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Which declaration creates a value that can never be reassigned?

    let creates a constant. Swift has no const keyword.
  2. 2. What type does Swift infer for let price = 9.99?

    Floating-point literals default to Double.
  3. 3. Which line needs a type annotation?

    An empty collection literal has nothing to infer the element type from, so write for example let empty: [Int] = [].
  4. 4. What does the compiler do for a var that is never mutated?

    The program compiles, but the warning tells you the var can become a let.
  5. 5. After let box = Crate(size: 1) where Crate is a class with a var size, is box.size = 5 allowed?

    For class instances, let only prevents pointing box at a different object; var properties can still change.

Summary

  • let declares a constant, var a variable; prefer let and switch to var only when needed.
  • Swift infers types from the initial value; the type then never changes.
  • Use a type annotation (name: Type) when the default is wrong, when inference lacks information, or to declare now and assign later.
  • A let can be assigned once after declaration if every path assigns it before use.
  • Use lowerCamelCase for values, UpperCamelCase for types; names should be clear at the point of use.
  • Inner scopes may shadow outer names, but redeclaring in the same scope is an error.
  • let on a class instance fixes the reference only; on value types it makes the contents immutable too.

Next: Basic Types