Type Annotations
In this page:
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
let age: Int = 25
let price: Double = 9.99
let name: String = "Swift"
print("\(name) costs \(price), age category \(age)")
Login to try C/C++/Java/PHP code in the editor
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
var total: Int
total = 100
print("Total is \(total)")
Login to try C/C++/Java/PHP code in the editor
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
let wholeNumber: Double = 5
print("Forced to Double: \(wholeNumber)")
Login to try C/C++/Java/PHP code in the editor
- Adding a type annotation to every single variable out of habit, even when inference already makes it obvious and annotation adds no clarity.
- Writing the annotation but supplying a value of an incompatible type, e.g.
let age: Int = "25". - Forgetting the colon syntax and writing
let age Int = 25instead oflet age: Int = 25.
- A type annotation uses
: Typeafter 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
Doubleinstead of the inferredInt. - 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: