Menu
Coddy logo textTech

Type Annotations

Part of the Fundamentals section of Coddy's Swift journey — lesson 5 of 86.

Swift can automatically figure out the type of a value. This is called type inference:

let name = "Alice"   // Swift infers this is a String
let age = 25         // Swift infers this is an Int
let price = 9.99     // Swift infers this is a Double

But you can also explicitly declare the type using a type annotation. You write a colon after the name, followed by the type:

let name: String = "Alice"
let age: Int = 25
let price: Double = 9.99
let isActive: Bool = true

Type annotations are useful when:

  • You want to be extra clear about what type a value is
  • You declare a variable without an initial value
var score: Int   // Declared but not yet assigned
score = 100      // Assigned later

Without the type annotation, Swift wouldn't know what type score should be.

challenge icon

Challenge

Beginner

Create four constants with explicit type annotations:

  • name of type String with value "Alice"
  • age of type Int with value 30
  • price of type Double with value 9.99
  • isOnline of type Bool with value true

Print all four values on separate lines.

Cheat sheet

Swift can automatically determine the type of a value through type inference:

let name = "Alice"   // Swift infers String
let age = 25         // Swift infers Int
let price = 9.99     // Swift infers Double

You can explicitly declare types using type annotations with a colon after the variable name:

let name: String = "Alice"
let age: Int = 25
let price: Double = 9.99
let isActive: Bool = true

Type annotations are useful when declaring a variable without an initial value:

var score: Int   // Declared but not assigned
score = 100      // Assigned later

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals