In addition to the operators described in Basic Operators, Swift provides several advanced operators that perform more complex value manipulation. These include all of the bitwise and bit shifting operators you will be familiar with from C and Objective-C.
Unlike arithmetic operators in C, arithmetic operators in Swift do not overflow by default. Overflow behavior is trapped and reported as an error. To opt in to overflow behavior, use Swift’s second set of arithmetic operators that overflow by default, such as the overflow addition operator (). All of these overflow operators begin with an ampersand ().
When you define your own structures, classes, and enumerations, it can be useful to provide your own implementations of the standard Swift operators for these custom types. Swift makes it easy to provide tailored implementations of these operators and to determine exactly what their behavior should be for each type you create.
You’re not limited to the predefined operators. Swift gives you the freedom to define your own custom infix, prefix, postfix, and assignment operators, with custom precedence and associativity values. These operators can be used and adopted in your code like any of the predefined operators, and you can even extend existing types to support the custom operators you define.
Bitwise operators enable you to manipulate the individual raw data bits within a data structure. They are often used in low-level programming, such as graphics programming and device driver creation. Bitwise operators can also be useful when you work with raw data from external sources, such as encoding and decoding data for communication over a custom protocol.
Swift supports all of the bitwise operators found in C, as described below.
Bitwise NOT Operator
The bitwise NOT operator () inverts all bits in a number:
The bitwise NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space:
integers have eight bits and can store any value between and . This example initializes a integer with the binary value , which has its first four bits set to , and its second four bits set to . This is equivalent to a decimal value of .
The bitwise NOT operator is then used to create a new constant called , which is equal to , but with all of the bits inverted. Zeros become ones, and ones become zeros. The value of is , which is equal to an unsigned decimal value of .
Bitwise AND Operator
The bitwise AND operator () combines the bits of two numbers. It returns a new number whose bits are set to only if the bits were equal to in both input numbers:
In the example below, the values of and both have four middle bits equal to . The bitwise AND operator combines them to make the number , which is equal to an unsigned decimal value of :
Bitwise OR Operator
The bitwise OR operator () compares the bits of two numbers. The operator returns a new number whose bits are set to if the bits are equal to in either input number:
In the example below, the values of and have different bits set to . The bitwise OR operator combines them to make the number , which equals an unsigned decimal of :
Bitwise XOR Operator
The bitwise XOR operator, or “exclusive OR operator” (), compares the bits of two numbers. The operator returns a new number whose bits are set to where the input bits are different and are set to where the input bits are the same:
In the example below, the values of and each have a bit set to in a location that the other does not. The bitwise XOR operator sets both of these bits to in its output value. All of the other bits in and match and are set to in the output value:
Bitwise Left and Right Shift Operators
The bitwise left shift operator () and bitwise right shift operator () move all bits in a number to the left or the right by a certain number of places, according to the rules defined below.
Bitwise left and right shifts have the effect of multiplying or dividing an integer by a factor of two. Shifting an integer’s bits to the left by one position doubles its value, whereas shifting it to the right by one position halves its value.
Shifting Behavior for Unsigned Integers
The bit-shifting behavior for unsigned integers is as follows:
Existing bits are moved to the left or right by the requested number of places.
Any bits that are moved beyond the bounds of the integer’s storage are discarded.
Zeros are inserted in the spaces left behind after the original bits are moved to the left or right.
This approach is known as a logical shift.
The illustration below shows the results of (which is shifted to the left by place), and (which is shifted to the right by place). Blue numbers are shifted, gray numbers are discarded, and orange zeros are inserted:
Here’s how bit shifting looks in Swift code:
You can use bit shifting to encode and decode values within other data types:
This example uses a constant called to store a Cascading Style Sheets color value for the color pink. The CSS color value is written as in Swift’s hexadecimal number representation. This color is then decomposed into its red (), green (), and blue () components by the bitwise AND operator () and the bitwise right shift operator ().
The red component is obtained by performing a bitwise AND between the numbers and . The zeros in effectively “mask” the second and third bytes of , causing the to be ignored and leaving as the result.
This number is then shifted 16 places to the right (). Each pair of characters in a hexadecimal number uses 8 bits, so a move 16 places to the right will convert into . This is the same as , which has a decimal value of .
Similarly, the green component is obtained by performing a bitwise AND between the numbers and , which gives an output value of . This output value is then shifted eight places to the right, giving a value of , which has a decimal value of .
Finally, the blue component is obtained by performing a bitwise AND between the numbers and , which gives an output value of . There’s no need to shift this to the right, as already equals , which has a decimal value of .
Shifting Behavior for Signed Integers
The shifting behavior is more complex for signed integers than for unsigned integers, because of the way signed integers are represented in binary. (The examples below are based on 8-bit signed integers for simplicity, but the same principles apply for signed integers of any size.)
Signed integers use their first bit (known as the sign bit) to indicate whether the integer is positive or negative. A sign bit of means positive, and a sign bit of means negative.
The remaining bits (known as the value bits) store the actual value. Positive numbers are stored in exactly the same way as for unsigned integers, counting upwards from . Here’s how the bits inside an look for the number :
The sign bit is (meaning “positive”), and the seven value bits are just the number , written in binary notation.
Negative numbers, however, are stored differently. They are stored by subtracting their absolute value from to the power of , where is the number of value bits. An eight-bit number has seven value bits, so this means to the power of , or .
Here’s how the bits inside an look for the number :
This time, the sign bit is (meaning “negative”), and the seven value bits have a binary value of (which is ):
This encoding for negative numbers is known as a two’s complement representation. It may seem an unusual way to represent negative numbers, but it has several advantages.
First, you can add to , simply by performing a standard binary addition of all eight bits (including the sign bit), and discarding anything that doesn’t fit in the eight bits once you’re done:
Second, the two’s complement representation also lets you shift the bits of negative numbers to the left and right like positive numbers, and still end up doubling them for every shift you make to the left, or halving them for every shift you make to the right. To achieve this, an extra rule is used when signed integers are shifted to the right: When you shift signed integers to the right, apply the same rules as for unsigned integers, but fill any empty bits on the left with the sign bit, rather than with a zero.
This action ensures that signed integers have the same sign after they are shifted to the right, and is known as an arithmetic shift.
Because of the special way that positive and negative numbers are stored, shifting either of them to the right moves them closer to zero. Keeping the sign bit the same during this shift means that negative integers remain negative as their value moves closer to zero.
If you try to insert a number into an integer constant or variable that cannot hold that value, by default Swift reports an error rather than allowing an invalid value to be created. This behavior gives extra safety when you work with numbers that are too large or too small.
For example, the integer type can hold any signed integer between and . Trying to set an constant or variable to a number outside of this range causes an error:
Providing error handling when values get too large or too small gives you much more flexibility when coding for boundary value conditions.
However, when you specifically want an overflow condition to truncate the number of available bits, you can opt in to this behavior rather than triggering an error. Swift provides three arithmetic overflow operators that opt in to the overflow behavior for integer calculations. These operators all begin with an ampersand ():
Overflow addition ()
Overflow subtraction ()
Overflow multiplication ()
Numbers can overflow in both the positive and negative direction.
Here’s an example of what happens when an unsigned integer is allowed to overflow in the positive direction, using the overflow addition operator ():
The variable is initialized with the maximum value a can hold (, or in binary). It is then incremented by using the overflow addition operator (). This pushes its binary representation just over the size that a can hold, causing it to overflow beyond its bounds, as shown in the diagram below. The value that remains within the bounds of the after the overflow addition is , or zero.
Something similar happens when an unsigned integer is allowed to overflow in the negative direction. Here’s an example using the overflow subtraction operator ():
The minimum value that a can hold is zero, or in binary. If you subtract from using the overflow subtraction operator (), the number will overflow and wrap around to , or in decimal.
Overflow also occurs for signed integers. All addition and subtraction for signed integers is performed in bitwise fashion, with the sign bit included as part of the numbers being added or subtracted, as described in Bitwise Left and Right Shift Operators.
The minimum value that an can hold is , or in binary. Subtracting from this binary number with the overflow operator gives a binary value of , which toggles the sign bit and gives positive , the maximum positive value that an can hold.
For both signed and unsigned integers, overflow in the positive direction wraps around from the maximum valid integer value back to the minimum, and overflow in the negative direction wraps around from the minimum value to the maximum.
Precedence and Associativity
Operator precedence gives some operators higher priority than others; these operators are applied first.
Operator associativity defines how operators of the same precedence are grouped together—either grouped from the left, or grouped from the right. Think of it as meaning “they associate with the expression to their left,” or “they associate with the expression to their right.”
It is important to consider each operator’s precedence and associativity when working out the order in which a compound expression will be calculated. For example, operator precedence explains why the following expression equals .
If you read strictly from left to right, you might expect the expression to be calculated as follows:
However, the actual answer is , not . Higher-precedence operators are evaluated before lower-precedence ones. In Swift, as in C, the remainder operator () and the multiplication operator () have a higher precedence than the addition operator (). As a result, they are both evaluated before the addition is considered.
However, remainder and multiplication have the same precedence as each other. To work out the exact evaluation order to use, you also need to consider their associativity. Remainder and multiplication both associate with the expression to their left. Think of this as adding implicit parentheses around these parts of the expression, starting from their left:
is , so this is equivalent to:
is , so this is equivalent to:
This calculation yields the final answer of .
For information about the operators provided by the Swift standard library, including a complete list of the operator precedence groups and associativity settings, see Operator Declarations.
Classes and structures can provide their own implementations of existing operators. This is known as overloading the existing operators.
The example below shows how to implement the arithmetic addition operator () for a custom structure. The arithmetic addition operator is a binary operator because it operates on two targets and is said to be infix because it appears in between those two targets.
The example defines a structure for a two-dimensional position vector , followed by a definition of an operator method to add together instances of the structure:
The operator method is defined as a type method on , with a method name that matches the operator to be overloaded (). Because addition isn’t part of the essential behavior for a vector, the type method is defined in an extension of rather than in the main structure declaration of . Because the arithmetic addition operator is a binary operator, this operator method takes two input parameters of type and returns a single output value, also of type .
In this implementation, the input parameters are named and to represent the instances that will be on the left side and right side of the operator. The method returns a new instance, whose and properties are initialized with the sum of the and properties from the two instances that are added together.
The type method can be used as an infix operator between existing instances:
This example adds together the vectors and to make the vector , as illustrated below.
Prefix and Postfix Operators
The example shown above demonstrates a custom implementation of a binary infix operator. Classes and structures can also provide implementations of the standard unary operators. Unary operators operate on a single target. They are prefix if they precede their target (such as ) and postfix operators if they follow their target (such as ).
You implement a prefix or postfix unary operator by writing the or modifier before the keyword when declaring the operator method:
The example above implements the unary minus operator () for instances. The unary minus operator is a prefix operator, and so this method has to be qualified with the modifier.
For simple numeric values, the unary minus operator converts positive numbers into their negative equivalent and vice versa. The corresponding implementation for instances performs this operation on both the and properties:
Compound Assignment Operators
Compound assignment operators combine assignment () with another operation. For example, the addition assignment operator () combines addition and assignment into a single operation. You mark a compound assignment operator’s left input parameter type as , because the parameter’s value will be modified directly from within the operator method.
The example below implements an addition assignment operator method for instances:
Because an addition operator was defined earlier, you don’t need to reimplement the addition process here. Instead, the addition assignment operator method takes advantage of the existing addition operator method, and uses it to set the left value to be the left value plus the right value:
Custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator () and “not equal to” operator (). It is not possible for Swift to guess what would qualify as “equal” for your own custom types, because the meaning of “equal” depends on the roles that those types play in your code.
To use the equivalence operators to check for equivalence of your own custom type, provide an implementation of the operators in the same way as for other infix operators:
The above example implements an “equal to” operator () to check if two instances have equivalent values. In the context of , it makes sense to consider “equal” as meaning “both instances have the same values and values”, and so this is the logic used by the operator implementation. The example also implements the “not equal to” operator (), which simply returns the inverse of the result of the “equal to” operator.
You can now use these operators to check whether two instances are equivalent:
You can declare and implement your own custom operators in addition to the standard operators provided by Swift. For a list of characters that can be used to define custom operators, see Operators.
New operators are declared at a global level using the keyword, and are marked with the , or modifiers:
The example above defines a new prefix operator called . This operator does not have an existing meaning in Swift, and so it is given its own custom meaning below in the specific context of working with instances. For the purposes of this example, is treated as a new “prefix doubling” operator. It doubles the and values of a instance, by adding the vector to itself with the addition assignment operator defined earlier. To implement the operator, you add a type method called to as follows:
Precedence for Custom Infix Operators
Custom infix operators each belong to a precedence group. A precedence group specifies an operator’s precedence relative to other infix operators, as well as the operator’s associativity. See Precedence and Associativity for an explanation of how these characteristics affect an infix operator’s interaction with other infix operators.
A custom infix operator that is not explicitly placed into a precedence group is given a default precedence group with a precedence immediately higher than the precedence of the ternary conditional operator.
The following example defines a new custom infix operator called , which belongs to the precedence group :
This operator adds together the values of two vectors, and subtracts the value of the second vector from the first. Because it is in essence an “additive” operator, it has been given the same precedence group as additive infix operators such as and . For information about the operators provided by the Swift standard library, including a complete list of the operator precedence groups and associativity settings, see Operator Declarations. For more information about precedence groups and to see the syntax for defining your own operators and precedence groups, see Operator Declaration.
About the Language Reference
Operator overloading (less commonly known as ad-hoc polymorphism) is a specific case of polymorphism (part of the OO nature of the language) in which some or all operators like , or are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. Operator overloading is usually only syntactic sugar. It can easily be emulated using function calls.
Consider this operation:
Using operator overloading permits a more concise way of writing it, like this:a + b * c
(Assuming the operator has higher precedence than .)
Operator overloading can provide more than an aesthetic benefit, since the language allows operators to be invoked implicitly in some circumstances. Problems, and critics, to the use of operator overloading arise because it allows programmers to give operators completely free functionality, without an imposition of coherency that permits to consistently satisfy user/reader expectations. Usage of the operator is an example of this problem.
Will return twice the value of if is an integer variable, but if is an output stream instead this will write "1" to it. Because operator overloading allows the programmer to change the usual semantics of an operator, it is usually considered good practice to use operator overloading with care.
To overload an operator is to provide it with a new meaning for user-defined types. This is done in the same fashion as defining a function. The basic syntax follows (where @ represents a valid operator):
Not all operators may be overloaded, new operators cannot be created, and the precedence, associativity or arity of operators cannot be changed (for example ! cannot be overloaded as a binary operator). Most operators may be overloaded as either a member function or non-member function, some, however, must be defined as member functions. Operators should only be overloaded where their use would be natural and unambiguous, and they should perform as expected. For example, overloading + to add two complex numbers is a good use, whereas overloading * to push an object onto a vector would not be considered good style.
- A simple Message Header
Operators as member functions
Aside from the operators which must be members, operators may be overloaded as member or non-member functions. The choice of whether or not to overload as a member is up to the programmer. Operators are generally overloaded as members when they:
- change the left-hand operand, or
- require direct access to the non-public parts of an object.
When an operator is defined as a member, the number of explicit parameters is reduced by one, as the calling object is implicitly supplied as an operand. Thus, binary operators take one explicit parameter and unary operators none. In the case of binary operators, the left hand operand is the calling object, and no type coercion will be done upon it. This is in contrast to non-member operators, where the left hand operand may be coerced.
- + (addition)
- - (subtraction)
- * (multiplication)
- / (division)
- % (modulus)
As binary operators, these involve two arguments which do not have to be the same type. These operators may be defined as member or non-member functions. An example illustrating overloading for the addition of a 2D mathematical vector type follows.
It is good style to only overload these operators to perform their customary arithmetic operation. Because operator has been overloaded as member function, it can access private fields.
- ^ (XOR)
- | (OR)
- & (AND)
- ~ (complement)
- << (shift left, insertion to stream)
- >> (shift right, extraction from stream)
All of the bitwise operators are binary, except complement, which is unary. It should be noted that these operators have a lower precedence than the arithmetic operators, so if ^ were to be overloaded for exponentiation, x ^ y + z may not work as intended. Of special mention are the shift operators, << and >>. These have been overloaded in the standard library for interaction with streams. When overloading these operators to work with streams the rules below should be followed:
- overload << and >> as friends (so that it can access the private variables with the stream be passed in by references
- (input/output modifies the stream, and copying is not allowed)
- the operator should return a reference to the stream it receives (to allow chaining, cout << 3 << 4 << 5)
- An example using a 2D vector
The assignment operator, =, must be a member function, and is given default behavior for user-defined classes by the compiler, performing an assignment of every member using its assignment operator. This behavior is generally acceptable for simple classes which only contain variables. However, where a class contains references or pointers to outside resources, the assignment operator should be overloaded (as general rule, whenever a destructor and copy constructor are needed so is the assignment operator), otherwise, for example, two strings would share the same buffer and changing one would change the other.
In this case, an assignment operator should perform two duties:
- clean up the old contents of the object
- copy the resources of the other object
For classes which contain raw pointers, before doing the assignment, the assignment operator should check for self-assignment, which generally will not work (as when the old contents of the object are erased, they cannot be copied to refill the object). Self assignment is generally a sign of a coding error, and thus for classes without raw pointers, this check is often omitted, as while the action is wasteful of cpu cycles, it has no other effect on the code.
Another common use of overloading the assignment operator is to declare the overload in the private part of the class and not define it. Thus any code which attempts to do an assignment will fail on two accounts, first by referencing a private member function and second fail to link by not having a valid definition. This is done for classes where copying is to be prevented, and generally done with the addition of a privately declared copy constructor
- == (equality)
- != (inequality)
- > (greater-than)
- < (less-than)
- >= (greater-than-or-equal-to)
- <= (less-than-or-equal-to)
All relational operators are binary, and should return either true or false. Generally, all six operators can be based off a comparison function, or each other, although this is never done automatically (e.g. overloading > will not automatically overload < to give the opposite). There are, however, some templates defined in the header <utility>; if this header is included, then it suffices to just overload operator== and operator<, and the other operators will be provided by the STL.
- ! (NOT)
- && (AND)
- || (OR)
The logical operators AND are used when evaluating two expressions to obtain a single relational result.The operator corresponds to the boolean logical operation AND,which yields true if operands are true,and false otherwise.The following panel shows the result of operator evaluating the expression.
The ! operator is unary, && and || are binary. It should be noted that in normal use, && and || have "short-circuit" behavior, where the right operand may not be evaluated, depending on the left operand. When overloaded, these operators get function call precedence, and this short circuit behavior is lost. It is best to leave these operators alone.
If the result of Function1() is false, then Function2() is not called.
Both Function3() and Function4() will be called no matter what the result of the call is to Function3() This is a waste of CPU processing, and worse, it could have surprising unintended consequences compared to the expected "short-circuit" behavior of the default operators. Consider:
Compound assignment operators
- += (addition-assignment)
- -= (subtraction-assignment)
- *= (multiplication-assignment)
- /= (division-assignment)
- %= (modulus-assignment)
- &= (AND-assignment)
- |= (OR-assignment)
- ^= (XOR-assignment)
- <<= (shift-left-assignment)
- >>= (shift-right-assignment)
Compound assignment operators should be overloaded as member functions, as they change the left-hand operand. Like all other operators (except basic assignment), compound assignment operators must be explicitly defined, they will not be automatically (e.g. overloading = and + will not automatically overload +=). A compound assignment operator should work as expected: A @= B should be equivalent to A = A @ B. An example of += for a two-dimensional mathematical vector type follows.
Increment and decrement operators
- ++ (increment)
- -- (decrement)
Increment and decrement have two forms, prefix (++i) and postfix (i++). To differentiate, the postfix version takes a dummy integer. Increment and decrement operators are most often member functions, as they generally need access to the private member data in the class. The prefix version in general should return a reference to the changed object. The postfix version should just return a copy of the original value. In a perfect world, A += 1, A = A + 1, A++, ++A should all leave A with the same value.
Often one operator is defined in terms of the other for ease in maintenance, especially if the function call is complex.
The subscript operator, [ ], is a binary operator which must be a member function (hence it takes only one explicit parameter, the index). The subscript operator is not limited to taking an integral index. For instance, the index for the subscript operator for the std::map template is the same as the type of the key, so it may be a string etc. The subscript operator is generally overloaded twice; as a non-constant function (for when elements are altered), and as a constant function (for when elements are only accessed).
Function call operator
The function call operator, ( ), is generally overloaded to create objects which behave like functions, or for classes that have a primary operation. The function call operator must be a member function, but has no other restrictions - it may be overloaded with any number of parameters of any type, and may return any type. A class may also have several definitions for the function call operator.
Address of, Reference, and Pointer operators
These three operators, operator&(), operator*() and operator->() can be overloaded. In general these operators are only overloaded for smart pointers, or classes which attempt to mimic the behavior of a raw pointer. The pointer operator, operator->() has the additional requirement that the result of the call to that operator, must return a pointer, or a class with an overloaded operator->(). In general A == *&A should be true.
Note that overloading operator& invokes undefined behavior:
- ISO/IEC 14882:2003, Section 5.3.1
- The address of an object of incomplete type can be taken, but if the complete type of that object is a class type that declares operator&() as a member function, then the behavior is undefined (and no diagnostic is required).
These are extremely simplified examples designed to show how the operators can be overloaded and not the full details of a SmartPointer or SmartReference class. In general you won't want to overload all three of these operators in the same class.
The comma operator,() , can be overloaded. The language comma operator has left to right precedence, the operator,() has function call precedence, so be aware that overloading the comma operator has many pitfalls.
For non overloaded comma operator, the order of execution will be Function1(), Function2(); With the overloaded comma operator, the compiler can call either Function1(), or Function2() first.
Member Reference operators
The two member access operators, operator->() and operator->*() can be overloaded. The most common use of overloading these operators is with defining expression template classes, which is not a common programming technique. Clearly by overloading these operators you can create some very unmaintainable code so overload these operators only with great care.
When the -> operator is applied to a pointer value of type (T *), the language dereferences the pointer and applies the . member access operator (so x->m is equivalent to (*x).m). However, when the -> operator is applied to a class instance, it is called as a unary postfix operator; it is expected to return a value to which the -> operator can again be applied. Typically, this will be a value of type (T *), as in the example under Address of, Reference, and Pointer operators above, but can also be a class instance with operator->() defined; the language will call operator->() as many times as necessary until it arrives at a value of type (T *).
Memory management operators
- new (allocate memory for object)
- new[ ] (allocate memory for array)
- delete (deallocate memory for object)
- delete[ ] (deallocate memory for array)
The memory management operators can be overloaded to customize allocation and deallocation (e.g. to insert pertinent memory headers). They should behave as expected, new should return a pointer to a newly allocated object on the heap, delete should deallocate memory, ignoring a NULL argument. To overload new, several rules must be followed:
- new must be a member function
- the return type must be void*
- the first explicit parameter must be a size_t value
To overload delete there are also conditions:
- delete must be a member function (and cannot be virtual)
- the return type must be void
- there are only two forms available for the parameter list, and only one of the forms may appear in a class:
Conversion operators enable objects of a class to be either implicitly (coercion) or explicitly (casting) converted to another type. Conversion operators must be member functions, and should not change the object which is being converted, so should be flagged as constant functions. The basic syntax of a conversion operator declaration, and declaration for an int-conversion operator follows.
Notice that the function is declared without a return-type, which can easily be inferred from the type of conversion. Including the return type in the function header for a conversion operator is a syntax error.
Operators which cannot be overloaded
- ?: (conditional)
- . (member selection)
- .* (member selection with pointer-to-member)
- :: (scope resolution)
- (object size information)
- typeid (object type information)
To understand the reasons why the language doesn't permit these operators to be overloaded, read "Why can't I overload dot, ::, , etc.?" at the Bjarne Stroustrup's C++ Style and Technique FAQ ( http://www.stroustrup.com/bs_faq2.html#overload-dot ).