Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Declare Variables in Swift
Written by Team Kodeco

In Swift, variables are used to store values that can change throughout the course of a program. They are declared using the var keyword, followed by the variable name and an equal sign, and then the value being assigned to the variable. Here is an example:

var age = 42

This declares a variable named age and assigns it the value of 25. You can then change the value of the variable later in your code:

age = 42

You can also declare a variable without assigning it a value initially. This is called an “uninitialized” variable. An uninitialized variable must be assigned a value before it’s used in your code, otherwise you’ll get a compile-time error. Here is an example:

var name: String
name = "Ray"

Note that when you declare a variable without assigning it a value initially, you have to use an explicit type annotation to specify the type of the variable. In the example above, you specified that name was of type String.

You can also declare multiple variables on a single line, separated by commas:

var name = "Ray", age = 42

Variable Name Restrictions

It’s important to note that the variable name cannot start with a number and it shouldn’t contain any whitespaces, mathematical symbols or arrows and it should start with a letter or underscore.

It’s also important to note that a variable can only be declared once within the same scope. Attempting to declare the same variable again within the same scope will result in a compile-time error.

© 2024 Kodeco Inc.