Swift Introduction | Values, Variables, and Operations | Basic Operations

Operations on values use familiar operators. This article introduces the main operators.

Numeric Operations

Use the standard arithmetic operators.

Expression Description
A + B Add B to A.
A - B Subtract B from A.
A * B Multiply A by B.
A / B Divide A by B.
A % B Calculate the remainder after dividing A by B.

Use parentheses to control precedence when necessary.

Text Operations

Use the plus sign (+) to concatenate text. For example, "Hello" + "Swift" produces "HelloSwift".

Assignment Operators

Use the equals sign (=) to assign the value on the right to the variable on the left. The following operators combine arithmetic with assignment.

Expression Description
A += B Add B to A. Equivalent to A = A + B.
A -= B Subtract B from A. Equivalent to A = A - B.
A *= B Multiply A by B. Equivalent to A = A * B.
A /= B Divide A by B. Equivalent to A = A / B.
A %= B Assign the remainder after dividing A by B. Equivalent to A = A % B.

Increment and Decrement Operators

These operators increase or decrease a variable by one.

Expression Description
++A, A++ Increase A by one.
–A, A– Decrease A by one.

An operator can appear before or after a variable. The difference is the timing of evaluation and update. ++A increments the value before retrieving it, while A++ retrieves the value before incrementing it.

Comparison Operators

Comparison operators compare two values and return true or false.

Expression Description
A == B A and B are equal.
A != B A and B are not equal.
A < B A is less than B.
A <= B A is less than or equal to B.
A > B A is greater than B.
A >= B A is greater than or equal to B.

Logical Operators

Logical operators accept Boolean values and return Boolean values. They are useful for combining conditions.

Expression Description
A && B AND: true only if both A and B are true.
A || B OR: true if either A or B is true.
A ^ B XOR: true if A and B differ.
!A NOT: reverses the Boolean value of A.