Type Annotations
In this page:
let name: Type = value
var name: Type // no value yet
name = value
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
// Declare a constant `age` (an Int), set to `25`
let age: Int = 25
// Declare a constant `price` (a Double), set to `9.99`
let price: Double = 9.99
// Declare a constant `name` (a String), set to `"Swift"`
let name: String = "Swift"
// Print "\(name) costs \(price), age category \(age)" to the console
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)" to the console
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.
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: