Constants, Variables, Type Annotations, Print, Comments and Semicolons - Swift Programming Language

Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.

1. Declaring Constants and Variables

Constants are declared using the let keyword, and variables with the var keyword. Always use let instead of var if the value of the variable will not change.

Here’s an example of how constants and variables can be used to track the number of login attempts a user has made:

let maximumNumberOfLoginAttempts = 10  
var currentLoginAttempt = 0  

This code can be read as: Declare a new constant called maximumNumberOfLoginAttempts, and give it a value of 10. Then, declare a new variable called currentLoginAttempt, and give it an initial value of 0.

In this example, the maximum number of allowed login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented after each failed login attempt.

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

var x = 0.0, y = 0.0, z = 0.0  

NOTE:- If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

2. Type Annotations

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.

This example provides a type annotation for a variable called welcomeMessage, to indicate that the variable can store String values:

var welcomeMessage: String  

This code can be read as: Declare a variable called welcomeMessage that is of type String. The welcomeMessage variable can now be set to any string value without error:

welcomeMessage = "Hello"  

You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:

var red, green, blue: Double  

3. Naming Constants and Variables

Constant and variable names can contain almost any character, including Unicode characters:

let π = 3.14159  
let 你好 = "你好世界"  
let 🐶🐮 = "dogcow"  

Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters.

Once you’ve declared a constant or variable of a certain type, you can’t redeclare it again with the same name, or change it to store values of a different type. Nor can you change a constant into a variable or a variable into a constant.

You can change the value of an existing variable to another value of a compatible type. In this example, the value of friendlyWelcome is changed from "Hello!" to "Bonjour!":

var friendlyWelcome = "Hello!"  
friendlyWelcome = "Bonjour!"  
// friendlyWelcome is now "Bonjour!"

Unlike a variable, the value of a constant cannot be changed once it is set. Attempting to do so is reported as an error when your code is compiled:

let languageName = "Swift"  
languageName = "Swift++"  
// This is a compile-time error: languageName cannot be changed.

4. Printing Constants and Variables

You can print the current value of a constant or variable with the print(_:separator:terminator:) function:

// Prints "Bonjour!"

The print(_:separator:terminator:) function is a global function that prints one or more values to an appropriate output. In Xcode, for example, the print(_:separator:terminator:) function prints its output in Xcode’s “console” pane. The separator and terminator parameter have default values, so you can omit them when you call this function. By default, the function terminates the line it prints by adding a line break. To print a value without a line break after it, pass an empty string as the terminator—for example, print(_:separator:terminator:).

Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis:

print("The current value of friendlyWelcome is \(friendlyWelcome)")  
// Prints "The current value of friendlyWelcome is Bonjour!"


Use comments to include nonexecutable text in your code, as a note or reminder to yourself. Comments are ignored by the Swift compiler when your code is compiled.

Comments in Swift are very similar to comments in C.

5.1 Single-line Comments

Single-line comments begin with two forward-slashes (//):

// This is a comment.

5.2 Multiline Comments

Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/):

/* This is also a comment
but is written over multiple lines. */  

5.3 Nested Multiline Comments

Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block:

/* This is the start of the first multiline comment.
 /* This is the second, nested multiline comment. */
 This is the end of the first multiline comment. */

Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.

6. Semicolons

Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. However, semicolons are required if you want to write multiple separate statements on a single line:

let cat = "🐱"; print(cat)

// Prints "🐱"

Swift Playground Example Download

// this is a single line comment using two slashes.

/* this is also a comment,
but written over multiple lines */

/* multiline comments
/* can be nested! */
Therefore you can block out code containing multiline  

// Swift variables are declared with "var"
// this is followed by a name, a type, and a value
var explicitDouble: Double = 70

// If the type is omitted, Swift will infer it from
// the variable's initial value
var implicitInteger = 70  
var implicitDouble = 70.0  
var 國 = "美國"

// Swift constants are declared with "let"
// followed by a name, a type, and a value
let numberOfBananas: Int = 10

// Like variables, if the type of a constant is omitted,
// Swift will infer it from the constant's value
let numberOfApples = 3  
let numberOfOranges = 5

// Values of variables and constants can both be
// interpolated in strings as follows
let appleSummary = "I have \(numberOfApples) apples."  
let fruitSummary = "I have \(numberOfApples + numberOfOranges) pieces of fruit."

// In "playgrounds", code can be placed in the global scope
print("Hello, world")

// This is an array variable
var fruits = ["mango", "kiwi", "avocado"]

// Example of an if statement; .isEmpty, .count
if fruits.isEmpty {  
    print("No fruits in my array.")
} else {
    print("There are \(fruits.count) items in my array")

// Define a dictionary with four items:
// Each item has a person's name and age
let people = ["Anna": 67, "Beto": 8, "Jack": 33, "Sam": 25]

// Now we use Swift's flexible enumerator system
// to extract both values in a single loop
for (name, age) in people {  
    print("\(name) is \(age) years old.")

// Functions and methods are both declared with the
// "func" syntax, and the return type is specified with ->
func sayHello(personName: String) -> String {  
    let greeting = "Hello, \(personName)!"
    return greeting

// prints "Hello, Dilan!"
print(sayHello(personName: "Dilan"))

// Parameter names can be made external and required
// for calling.
// The external name can be the same as the parameter
// name by prefixing with an octothorpe (#)
// - or it can be defined separately.

func sayAge(personName: String, personAge age: Int) -> String {  
    let result = "\(personName) is \(age) years old."
    return result

// We can also specify the name of the parameter

print(sayAge(personName: "Dilan", personAge: 42))  

Next - Int by Example

Related Article