0
0
Swiftprogramming~5 mins

Explicit type annotation in Swift

Choose your learning style9 modes available
Introduction

Explicit type annotation tells the computer exactly what kind of data a variable will hold. This helps avoid confusion and mistakes.

When you want to make your code clearer to others or yourself.
When the computer cannot guess the type on its own.
When you want to prevent accidental changes to the type later.
When you want to use a specific type instead of the default one.
When working with complex data or APIs that require exact types.
Syntax
Swift
var variableName: Type = value
let constantName: Type = value

Use var for variables that can change and let for constants that cannot change.

The colon : separates the name and the type.

Examples
Here, age is a variable holding an integer, and name is a constant holding a string.
Swift
var age: Int = 30
let name: String = "Alice"
Using Double for decimal numbers and Bool for true/false values.
Swift
var temperature: Double = 36.6
let isSunny: Bool = true
Explicitly stating that scores is an array of integers.
Swift
var scores: [Int] = [10, 20, 30]
Sample Program

This program shows variables and constants with explicit types. It prints their values clearly.

Swift
import Foundation

var height: Double = 1.75
let greeting: String = "Hello, Swift!"
var isActive: Bool = false

print("Height: \(height) meters")
print(greeting)
print("Active status: \(isActive)")
OutputSuccess
Important Notes

Explicit type annotation is optional if Swift can guess the type from the value.

Using explicit types can help catch errors early when the wrong type is assigned.

Summary

Explicit type annotation tells the exact data type of a variable or constant.

It improves code clarity and safety.

Use it when you want to be clear or when Swift cannot guess the type.