Operators - FUNDAMENTALS - Understanding Swift Programming: Swift 2 (2015)

Understanding Swift Programming: Swift 2 (2015)

PART 1: FUNDAMENTALS

4. Operators

The most basic part of most programming languages is the statement, with its variables, constants, literal values and, above all, the operators that serve as the glue that holds the statement together:

var c = a + 37

Here we have the addition operator ("+") that we all learned about in elementary school, and also the assignment operator ("="), the latter used in programming but not in mathematics.

What is an operator? An operator is a symbol representing an operation that produces a result from one or more operands. An operand is a value that may be in the form of a variable, constant, expression, or literal value. The symbol for an operator is usually one or two special characters, but can also be a word. For example, Swift includes the operator is, used in type checking, or determining the type of a variable.

Another way to look at an operator is as a function. Like a function, it takes input values and produces a return value.

Swift includes the typical operators that most C-like languages have, plus a few new ones, including the range operators . . . and . .< and the type checking and type casting operators is, as?, and as! Most operators work like those in other languages, but a few do not. The remainder ("%") operator in Swift can produce floating point values, and the arithmetic operators do not allow underflow or overflow (that is, producing a result that is larger or smaller than the type can represent.)

Arithmetic Operators

Operators are typically divided into groups, according to the number of operands each operator uses. The defined Swift arithmetic operators are as follows.

Operators with a single operand (unary operators).

- Minus

++ Increment

-- Decrement

! Negation

+ Plus

Unary operators must be placed immediately adjacent to their operand, with no intervening whitespace. Thus:

var a = -5

is correct, while

var a = - 8 // Compiler error

is not correct.

Operators with two operands (binary operators).

+ Add

- Subtract

/ Divide

* Multiply

% Remainder

The remainder operator works "sort of" like division. Imagine a being divided by b. The highest integer that can be multiplied by b and still be less than a is found. This is then subtracted from a to produce the remainder. This operator in Swift will, unlike other languages, produce a remainder that is a floating point number, if the operands are floating point types. Thus, for integer types:

var a = 7 // Compiler infers a to be an Int

var b = 2 // Highest number is 3 to be multiplied by 2

var c = a % b // Result is 1

For floating point types:

var a = 8.0 // Compiler infers a to be a Double

var b = 1.5 // Highest number is 5 to be multiplied by 1.5

var c = a % b // Result is 0.5

Operators can also be placed in different positions relative to operands. In the case of operators with only a single operand, there are two possibilities: prefix and postfix:

++a // Prefix

a++ // Postfix

Whether an operator is in the prefix or postfix position often does make a difference. In the case of the increment operator, we can see this with the code below:

var m = 5

print(++m) // Prints: 6

var n = 5

print(n++) // Prints: 5

In the first example of printing ++m, the increment is done and then the expression evaluated before printing, with the expression value 6. In the second example of printing n++, the expression is evaluated first, yielding a value of 5, and the increment is done afterwards.

In the case of operators with two operands, there is only one possibility: infix:

a + b // Infix

Comparison Operators

Swift has six comparison operators that each compare two values. These are used in C and many similar languages:

== Equal

!= Not equal

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

Each operator is used in an expression with two operands and tests whether the comparison is true or false, yielding a Boolean true or false value.

Thus, the expression

4 == 5

is false, while

"George" == "George"

is true.

The result of such an expression can be assigned to a variable:

var result: Bool = 3 == 5

Although perfectly legitimate, this looks a bit odd and it is common to put parentheses around such expressions to make them easier to read:

var result: Bool = (3 == 5)

Comparison operators are commonly used directly in conditional expressions:

if x >= 5 { print ("x is greater than or equal to 5") }

Logical Operators

&& // AND

|| // OR

! // NOT

Other Operators

Operators with two operators (binary operators)

..< Half-open Range

... Closed Range

?? Nil Coalescing Operator

Operators with three operands (tenary operators).

? : Ternary

The range operators were discussed in Chapter 2 on "Fundamentals", while the Nil Coalescing Operator will be discussed in Chapter 9 on Optional Values.

The "ternary condition operator" uses two symbols. The expression to the left of the ? symbol is evaluated. If it is true, the statement just to the right of the ? symbol is executed; otherwise the statement just to the right of the : symbol is executed.

Operator Precedence

When more than one operator is in a statement, the issue comes up of what order the operators are executed in. Swift, like other C-like languages, evaluates expressions from left to right.

Consider the following statement:

a = 2 + 3 * 6

If we follow a strict left-to-right evaluation, a will be assigned a value of 30.

However, Swift, like most C-like languages, gives some operators precedence over others, in particular, multiplication over addition. So in the statement above, a will be set to 20, not 30.

Swift's compiler has a number that indicates the precedence levels, as follows:

Multiply and Divide 150

Addition and Subtraction 140

Range 135

Type check and Type cast 132

Compound Assignment Operators

A compound assignment operator combines assignment with another operation. For example, to concatenate two strings:

nameOfMammallianSouthAmericanSpecies = "South American Jaguar"

nameOfMammallianSouthAmericanSpecies += ".txt"

Without the compound operator, you would have to use:

nameOfMammallianSouthAmericanSpecies = "South American Jaguar"

nameOfMammallianSouthAmericanSpecies = nameOfMammallianSouthAmericanSpecies + ".txt"

If you have a lot of long variable names in your code, this kind of operator will save you a lot of typing and make your code easier to read, once you get used to it. The assignment/addition operator is by far the most heavily used, but all of the following compound assignment operators can be used. They are shown along with their longer alternative.

a+=b a = b + a

a-=b a = b - a

a*=b a = b * a

a/=b a = b / a

Advanced Operators

In addition to the basic operators described above, Swift also has what Apple calls advanced operators. These include bitwise operators, bit shifting operators, and overflow operators. I'll describe these only briefly here, since they aren't that commonly used in apps. For details see the Apple documentation.

Bitwise Operators. The bitwise NOT operator ("~") inverts all of the bits in a binary number. (That is, changes the 1s to 0s and the 0s to 1s.) The bitwise AND operator ("&"), given two binary numbers, produces a third number which is a logical AND of the bits in the given numbers. The bitwise OR operator ("|"), given two binary numbers, produces a third number which is a logical OR of the bits in the given numbers. The bitwise XOR operator ("^"), given two binary numbers, produces a third number which is a logical XOR, that is, an exclusive OR, of the bits in the given numbers.

Bit Shifting Operators. The bitwise left shift operator ("<<") moves all of the bits in a binary number a specified number of places to the left. The bitwise right shift operator (">>") moves all of the bits in a binary number a specified number of places to the right.

Overflow Operators. The overflow operators "&+", "&-", "&*", "&/", and "&%" prevent triggering a runtime exception that would otherwise occur, should the result of a computation be a value too large or too small to be stored in a particular integer type. The extraneous bits are truncated. &/ also allows division by zero without an exception, with the result set to 0.

Controversy Over Operators

Operators seem mostly straightforward, but there is still a little controversy over them. Mattt Thompson (NSHipster.com) questions using the "+" operator for concatenation as well as addition:

Why should adding two strings together concatenate them? 1 + 2 isn't 12 (except in JavaScript). Is this really intuitive, or is it just familiar?

The ternary condition operator, which doesn't even have a nice name, is hated by many programmers.

Hands-On Exercises

Go to the following web address with a Macintosh or Windows PC to do the Hands-On Exercises.

For Chapter 4 exercises, go to

understandingswiftprogramming.com/4