The Operators of the Swift Language - Swift Academy: The Stress Free Way To Learning Swift Inside & Out (2014)

Swift Academy: The Stress Free Way To Learning Swift Inside & Out (2014)

Chapter 4. The Operators of the Swift Language

In this chapter, you will learn about the operators available in Swift. Since you use operators in most of your codes, you have to study this material carefully. This chapter will help you master the basics of Swift in just two weeks.

Operators are special symbols or phrases that you can use to find, alter or merge values. For instance, you can use “+” to add two numbers (e.g. let x = 2 + 2). Some of the most complex operators are “&&” (known as the “logical AND operator”) and “++1” (called the “increment operator”).

This programming language uses most of the operators found in C. To prevent typical programming mistakes, Swift has made some improvements over the features currently offered by the C language. For instance, in Swift, the assignment operator (i.e. =) won’t give you any value. This is because many programmers mistakenly use it as the equal operator (i.e. ==). Additionally, mathematical operators can detect and prevent value overflows to make sure that the programmer won’t receive unexpected results when working with large numbers.

Swift allows you to conduct remainder computations on floating-point numeric values: this feature is not available in the C language. Also, Swift offers two operators that can help you in representing ranges of values.

Unary, Binary, and Ternary Operators

Each operator belongs to one of these categories:

· Unary – This category is composed of operators that can function on single targets only. Programmers divide unary operators into two subcategories:

o Prefix – A prefix operator appears before its target (eg. !x)

o Postfix – A postfix operator appears after its target (e.g. 6++)

· Binary – These operators work on two operands. Since these operators appear between the involved values, they are also called infix operators.

· Ternary – This category involves operators that work on three operands. The Swift programming language has one ternary operator, which is “?:”. Programmers refer to this operator as “ternary conditional.”

Important Note: The term “operand” refers to the values that the operators influence. In the mathematical expression “2 + 3 = 5,” 2 and 3 serve as the operands.

The Basic Operators

The Assignment Operator

This operator allows you to assign or replace values. In the example given below, “=” uses the value of “y” to update the value of “x”.

let y = 20

var x = 10

x = y

// now, x is equal to 20

If the right operand is a tuple that contains several different values, you may decompose it into its components. Here’s an example:

let (a, b) = (2, 4)

// a is equal to 2, and b is equal to 4

As discussed earlier, Swift’s assignment operator won’t give any value when used alone. The statement below will produce an error during compilation:

if a = b {

// This statement is invalid, since a = b won’t produce any value

}

The Arithmetic Operators

The Swift language supports the following mathematical operators:

· “+” – This operator allows you to add two operands.

· “-” – With this operator, you can subtract the value of the right operand from that of the left operand.

· “*” – You can use this operator to multiply the values of two operands.

· “/” – Use this operator to divide the left operand’s value by that of the right operand.

Important Note: By default, the arithmetic operators in Swift prevent value overflows.

The examples given below will show you how the mathematical operators work:

2 + 2 // is equal to 5

20 – 15 // is equal to 5

1 * 5 // is equal to 5

25 / 5 // is equal to 5

You may also use the addition operator to concatenate (i.e. combine) strings. Here’s an example:

“This” + “book” + “is” + “awesome” // is equal to “This book is awesome”

The Remainder Operator

With this operator, you can find out how many multiples of the right operator can fit in the left operator and determine the remainder. The example below will illustrate this concept:

10 % 6 // is equal to 4

Since 10 can only hold a single 6, the modulus operator will return 4 (i.e. the leftover value) as the remainder.

Remainder Computations for Floating-Point Values

In Swift, you can use the remainder operator when working with floating-point numeric values. Check the example below:

9 % 3.5 // is equal to 0.57

Here, 9 divided by 3.5 is equal to 2, with 0.57 as the remainder, thus, this operation will give you 0.57 as the result.

The Increment and Decrement Operators

Similar to the C language, Swift offers “++” (i.e. the increment operator) and “--” (i.e. the decrement operator) as shortcuts for increasing or decreasing values. The increment operator increases the value of a variable by 1. The decrement operator, on the other hand, decreases the value of a variable by 1. You may apply these operators on variables that hold an integer or floating-point value. Here’s the example:

var x = 1

++x // now, x is equal to 2

Swift allows you to use ++ and -- as prefix or postfix operators. That means in the statement given above, x++ will give you the same result (i.e. 2).

Important Note: Both the decrement and increment operators alter variables and give a value. If you simply want to increase or decrease the variable’s value, you may ignore the result of the operation. If you’ll use the resulting value, however, you will see some changes depending on which part of the variable you attached the operator to. Remember the following rules:

· If you’ll use the prefix version of the operator, it will increase/decrease the variable’s value before giving the result.

· If you’ll use the postfix version of the operator, it will increase/decrease the variable’s value after giving the result.

The Advanced Operators

The Range Operators

Here are the Swift operators that you can use to express ranges of values.

· (a…b) – Programmers refer to this operator as “closed range.” Basically, (a…b) specifies a range that goes from a to b. The range includes both the starting point and the endpoint.

· (a..b) – This operator is known as “half-closed range.” It specifies a range that goes from a to b. In this operation, “a” is included but “b” isn’t. That is the reason why people refer to it as “half-closed.”

The Logical Operators

A logical operator combines or alters true and false (i.e. the Boolean values). The Swift language offers the logical operators available in C. These operators are:

· “!” – This operator is called “logical NOT”. It allows you to reverse Boolean values. For example, you can use it to turn false into true, and true into false. You have to use it as a prefix operator. You will get an error message if place it at the end of the value you are modifying.

Here’s how it works: !false = true; !true = false

· “&&” – Programmers refer to this operator as “logical AND”. You can use it to write logical expressions where all of the values should be “true” in order to get “true” as the final result. If at least one of the values is false, the final result will be “false.” Actually, if the initial value is already false, the operator won’t even evaluate the rest of the expression. This process is called “short-circuit assessment/evaluation.”

· “||” – This infix operator is called “logical OR”. You can write it in your codes by typing two pipe characters. In general, you should use it for expressions where you can get “true” as the final result if at least one of the values is “true.”

Adding Parentheses

In some cases, it is beneficial to add parentheses even if they are not really necessary. By doing so, you can improve the readability of complex codes. Swift allows you to use this technique without changing other things in your codes. It is true that extra parentheses can make your codes longer. However, in developing apps and writing programs, readability is more important than conciseness. If you think a piece of code is confusing, go ahead and simplify it using some parentheses.