0
0
Swiftprogramming~5 mins

Var for variables (mutable) in Swift

Choose your learning style9 modes available
Introduction

Use var to create a variable that can change its value later. It helps you store information that might update.

When you want to keep track of a score that changes during a game.
When you need to store a user's name that can be updated.
When you want to count how many times a button is pressed.
When you want to store the current temperature that updates regularly.
When you want to remember a list size that can grow or shrink.
Syntax
Swift
var variableName: Type = initialValue

You can omit the type if you provide an initial value, and Swift will infer the type.

Variables declared with var can be changed later in the code.

Examples
Creates an integer variable named age with the value 25.
Swift
var age: Int = 25
Creates a string variable named name with the value "Alice". Type is inferred.
Swift
var name = "Alice"
Creates a variable score starting at 0, then changes it to 10.
Swift
var score = 0
score = 10
Sample Program

This program shows how a variable counter starts at 1 and then changes to 5.

Swift
var counter = 1
print("Counter is \(counter)")
counter = 5
print("Counter changed to \(counter)")
OutputSuccess
Important Notes

Use var only when you need to change the value. Otherwise, use let for constants.

Changing a var variable is easy and helps keep your program flexible.

Summary

var creates a variable that can change.

Variables store information that can update during the program.

Use var when you expect the value to change later.