...

/

Operators and Expressions

Operators and Expressions

Learn how to use variables and constants within Swift expressions to add logic to your code.

So far, we have looked at using variables and constants in Swift and also described the different data types. Being able to create variables, however, is only part of the story. The next step is to learn how to use these variables and constants in Swift code. The primary method for working with data is in the form of expressions.

Expression syntax in Swift

The most basic Swift expression consists of an operator, two operands, and an assignment. The following is an example of an expression:

var myresult = 1 + 2

In the above example, the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to a variable named myresult. The operands could just have easily been variables (or a mixture of constants and variables) instead of the actual numerical values used in the example.

Press + to interact
var myresult = 1 + 2
print(myresult)

In the remainder of this lesson, we will look at the basic types of operators available in Swift.

The basic assignment operator

We have already looked at the most basic of assignment operators, which is the = operator. This assignment operator simply assigns the result of an expression to a variable or constant. In essence, the = assignment operator takes two operands. The left-hand operand is the variable or constant to which a value is to be assigned, and the right-hand operand is the value to be assigned. The right-hand operand is more often than not an expression that performs some type of arithmetic or logical evaluation. The result of which will be assigned to the variable or constant. The following examples are all valid uses of the assignment operator:

Press + to interact
var x: Int? // Declare an optional Int variable
var y = 10 // Declare and initialize a second Int variable
x = 10 // Assign a value to x
print("x = \(x!)")
x = x! + y // Assign the result of x + y to x
print("x = \(x!)")
x = y // Assign the value of y to x
print("x = \(x!)")

Swift arithmetic operators

Swift provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators because they take two operands. The exception is the unary negative operator (-), which serves to indicate that a value is negative rather than positive. ...