Swift For Dummies
Book image
Explore Book Buy On Amazon

Whether symbols or text, operators in Swift act on operands, which are values — either specific values (such as 17.5) or expressions that yield values (such as 16.5 + 1). Combining an operator with the appropriate number of operands yields a value which can then be used itself as an operand in another operation.

Operands are sometimes referred to as the targets of operators. Whether you refer to them as operands, targets, or the more generic values, they may be single values such as 17.5 or the result of expressions.

Operators are classified by the number of operands on which they act, as follows:

  • Unary: Unary operators operate on one target. (The term target is often used to describe a unary operand.) In Swift they appear immediately before or after the operand. However, these are not interchangeable — for example, a minus sign must immediately precede a number and cannot follow a number. When a unary operator precedes its target, it’s called a prefix operator; when it follows its target, it’s called a postfix operator.

  • Binary: Binary operators operate on two targets. The basic arithmetic operators (+, -, /, and x) are binary operators. Whereas unary operators can be prefix or postfix operators, binary operators are infix operators because the operands (or targets) are placed on either side of the binary operator.

  • Ternary: Ternary operators operate on three targets. The classic ternary operator in C is also implemented in Swift. It describes a conditional operator using syntax such as the one shown here which evaluates to either the second or third value depending on the test in the condition:

(targetValue > 5) ? valueForLessThan5 : otherValue

In general, an operator is classified as one of these three. These concepts are present in many computer languages including most of those derived from C.

About This Article

This article is from the book:

About the book author:

Jesse Feiler is a developer, web designer, trainer, and author. He has worked with mobile devices starting with Apple’s Newton and continuing with the Apple’s iOS and OS X products, including the iPhone and iPad. He is heard regularly on WAMC Public Radio’s The Roundtable.

This article can be found in the category: