← Back to Swift Course | Chapter 2: Variables & Types | Lesson 3 of 8

Type Annotations

A type annotation is when you tell Swift exactly what kind of value a variable will hold, instead of letting it guess.

Basic Type Annotation Syntax

A type annotation follows the variable name with a colon and the type, making the intended type explicit rather than relying on inference.

Example: Basic Type Annotation Syntax

markup
let age: Int = 25
let price: Double = 9.99
let name: String = "Swift"
print("\(name) costs \(price), age category \(age)")

Declaring Without an Initial Value

When a variable is not given a value right away, a type annotation is required so Swift knows what type to expect once it is assigned.

Example: Declaring Without an Initial Value

markup
var total: Int
total = 100
print("Total is \(total)")

Forcing a Different Type Than Inference Would Choose

Sometimes you want a Double even though a whole number literal would normally infer as Int; an explicit annotation makes that choice for you.

Note: Without the annotation, let wholeNumber = 5 would be inferred as Int, not Double.

Example: Forcing a Different Type Than Inference Would Choose

markup
let wholeNumber: Double = 5
print("Forced to Double: \(wholeNumber)")
Common Mistakes
  1. Adding a type annotation to every single variable out of habit, even when inference already makes it obvious and annotation adds no clarity.
  2. Writing the annotation but supplying a value of an incompatible type, e.g. let age: Int = "25".
  3. Forgetting the colon syntax and writing let age Int = 25 instead of let age: Int = 25.
Chapter Summary
  • A type annotation uses : Type after the variable name, e.g. let age: Int.
  • Annotations are required when there's no initial value to infer from.
  • Annotations are useful for clarity, or to force a specific type like Double instead of the inferred Int.
  • The type after : must exactly match (or be convertible to) the assigned value.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.