Swift Multiple Variables

Swift Multiple Variables

Declare multiple variables or constants on one line when they share a type.


Multiple Variables Declared

Declaring multiple variables or constants on one line is only recommended if it stays easy to read.

Example

var x = 1, y = 2, z = 3
let a = 10, b = 20
print(x, y, z, a, b)

This example declares multiple variables and constants on one line.



With Type Annotations

Use explicit types when inference could be ambiguous or to document intent.

Example

var i: Int = 1, j: Int = 2
let firstName: String = "Robin", lastName: String = "Refsnes"
print(i + j, firstName, lastName)

This example declares multiple variables and constants on one line.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *