Type Inference
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
let age = 25
let price = 9.99
let name = "Swift"
print("\(name): age \(age), price \(price)")
Login to try C/C++/Java/PHP code in the editor
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
var count = 3
count = 10
print("count is now \(count), still an Int")
Login to try C/C++/Java/PHP code in the editor
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
let scores = [90, 85, 78]
print("Inferred as [Int]: \(scores)")
Login to try C/C++/Java/PHP code in the editor
- Believing Swift is untyped because you don't always write the type; every value still has a strict, fixed type behind the scenes.
- Assigning a value of one inferred type and later trying to assign a different type to the same variable, which fails to compile.
- Not realizing that mixing an Int literal with a Double in one expression forces an explicit conversion, since inference won't silently widen types.
- 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: