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

Type Inference

Type inference means Swift is smart enough to figure out what kind of value you're storing just by looking at it, without you having to say so.

How Inference Works

When you write let age = 25, Swift looks at the literal 25 and infers the type Int automatically, without you writing Int anywhere.

Example: How Inference Works

markup
let age = 25
let price = 9.99
let name = "Swift"
print("\(name): age \(age), price \(price)")

Types Are Still Fixed

Even though you didn't write the type explicitly, Swift still enforces it strictly -- a variable inferred as Int can never later hold a String.

Note: Try count = "ten" after this and the compiler will reject it -- that's inference plus strict typing working together.

Example: Types Are Still Fixed

markup
var count = 3
count = 10
print("count is now \(count), still an Int")

Inference with Collections

Type inference also works with arrays and dictionaries: Swift looks at the elements to infer the collection's element type.

Example: Inference with Collections

markup
let scores = [90, 85, 78]
print("Inferred as [Int]: \(scores)")
Common Mistakes
  1. Believing Swift is untyped because you don't always write the type; every value still has a strict, fixed type behind the scenes.
  2. Assigning a value of one inferred type and later trying to assign a different type to the same variable, which fails to compile.
  3. Not realizing that mixing an Int literal with a Double in one expression forces an explicit conversion, since inference won't silently widen types.
Chapter Summary
  • Swift infers a variable's type automatically from its initial value.
  • Once inferred, the type is fixed -- you cannot later assign a value of a different type.
  • Type inference reduces boilerplate while keeping Swift fully statically typed.
  • You can always check inferred behavior by trying to assign an incompatible type and seeing the compiler error.
🔒

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.