0
0
Swiftprogramming~5 mins

Type inference by the compiler in Swift

Choose your learning style9 modes available
Introduction

Type inference helps the computer guess the type of a value automatically. This makes your code shorter and easier to read.

When you want to write cleaner code without repeating types.
When the type of a value is obvious from the value itself.
When you want the compiler to help catch type mistakes early.
When you want to avoid cluttering your code with extra type information.
Syntax
Swift
let variableName = value
var variableName = value

The compiler looks at the value on the right side and decides the type.

You can use let for constants and var for variables.

Examples
The compiler knows number is an Int and message is a String.
Swift
let number = 10
var message = "Hello"
pi is inferred as Double and isActive as Bool.
Swift
let pi = 3.14
var isActive = true
The compiler infers names as an array of Strings.
Swift
let names = ["Anna", "Bob", "Cara"]
Sample Program

This program shows how the compiler guesses the types of different values automatically. It then prints them.

Swift
let age = 25
var greeting = "Hi there!"
let temperature = 22.5
var isSunny = false

print("Age is \(age)")
print(greeting)
print("Temperature: \(temperature)°C")
print("Is it sunny? \(isSunny)")
OutputSuccess
Important Notes

If the compiler cannot guess the type clearly, you must specify it yourself.

Type inference works best when the value is simple and clear.

Summary

Type inference lets the compiler guess variable types automatically.

This makes code shorter and easier to read.

You still can specify types if you want to be clear or need a specific type.