Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
variables
communitycreator

How to assign values to multiple variables at once in Swift

Theodore Kelechukwu Onyejiaku

Overview

We can assign values to multiple variables at once in a single statement in Swift. We need to wrap the variables inside a bracket and assign the values using the equal sign =. The values are also wrapped inside a bracket.

Syntax

(var1, var2, ...) = (val1, val2, ...)
Assigning multiple values to multiple variables in Swift

Parameters

  • var1, var2, ...: These are the variables we want to assign values to simultaneously.
  • val1, val2, ...: These are the values we want to assign to the variables.

Code

Let's look at the code below:

import Swift

// create some variables
var name = ""
var age = 0
var role = ""
var isMarried = false

// assign values at once
(name, age, role, isMarried) = ("Theodore", 200, "Software Deeveloper", true)

// print values
print(name)
print(age)
print(role)
print(isMarried)
Assigning values to multiple variables at a time in Swift

Explanation

In the code above:

  • Lines 4 to 7: We create some variables.
  • Line 10: We assign values to multiple variables at once.
  • Lines 13 to 16: We print the values of the newly assigned variables.

RELATED TAGS

swift
variables
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring