Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Assign Default Values to Variables
Written by Team Kodeco

In Swift, you can assign default values to variables when they are declared, which can be useful in situations where a variable may not be initialized with a value immediately. This allows for a default value to be used until a new value is assigned to the variable.

For example, to assign a default value of 0 to a variable of type Int, you can use the following syntax:

var numberOfApples = 0

In this example, numberOfApples is a variable of type Int that has been set to the default value of 0.

Similarly, you can assign a default value of an empty string to a variable of type String:

var message = ""

In this example, message is a variable of type String that has been set to the default value of an empty string.

Assigning default values to variables can be particularly useful in situations where a variable may not be initialized with a value immediately, such as when a variable is declared in a function or class.

© 2024 Kodeco Inc.