0
0
Swiftprogramming~10 mins

Explicit type annotation in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Explicit type annotation
Declare variable
Add explicit type annotation
Assign value matching type
Use variable in code
Compile checks type correctness
Run program with typed variable
This flow shows how you declare a variable with a specific type, assign a matching value, and then use it safely in your Swift code.
Execution Sample
Swift
var age: Int = 30
print(age)
Declare an integer variable 'age' with explicit type annotation and print its value.
Execution Table
StepActionVariableType AnnotationValueOutput
1Declare variable with typeageIntuninitialized
2Assign value 30ageInt30
3Print variableageInt3030
4End of program
💡 Program ends after printing the value of 'age'.
Variable Tracker
VariableStartAfter AssignmentFinal
ageuninitialized3030
Key Moments - 2 Insights
Why do we write ': Int' after the variable name?
The ': Int' tells Swift that 'age' must always hold an integer. This is shown in the execution_table step 1 where the type is set explicitly.
What happens if we assign a value of a different type?
Swift will give a compile error because the value does not match the declared type. This is checked before step 3 in the execution flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the value of 'age'?
Auninitialized
B30
C"30" as a string
Dnil
💡 Hint
Check the 'Value' column at step 2 in the execution_table.
At which step is the variable 'age' first given a value?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column for when assignment happens in the execution_table.
If we remove ': Int' from the declaration, what changes in the execution?
AThe program will not compile
BThe variable becomes a string
CSwift infers the type automatically
DThe variable cannot be used
💡 Hint
Swift can infer types if explicit annotation is missing, so check the concept_flow about type annotation necessity.
Concept Snapshot
Explicit type annotation in Swift:
var variableName: Type = value
- Declares variable with fixed type
- Helps catch type errors early
- Makes code clearer and safer
- Example: var age: Int = 30
Full Transcript
This visual execution shows how explicit type annotation works in Swift. First, a variable 'age' is declared with type Int. Then, the value 30 is assigned to it. The program prints the value 30. The type annotation ': Int' ensures the variable only holds integers, preventing errors. If a different type is assigned, Swift will stop compilation. This helps keep code safe and clear.