Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

The_Swift_Programming_Language

.pdf
Скачиваний:
24
Добавлен:
18.03.2015
Размер:
5 Мб
Скачать
☆

1

2

3

4

var potentialOverflow = Int16.max

//potentialOverflow equals 32767, which is the largest value an Int16 can hold potentialOverflow += 1

//this 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 five 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 (&*)

Overflow division (&/)

Overflow remainder (&%)

Value Overflow

Here’s an example of what happens when an unsigned value is allowed to overflow, using the overflow addition operator (&+):

1

2

3

4

var willOverflow = UInt8.max

//willOverflow equals 255, which is the largest value a UInt8 can hold willOverflow = willOverflow &+ 1

//willOverflow is now equal to 0

The variable willOverflow is initialized with the largest value a UInt8 can hold (255, or 11111111 in binary). It is then incremented by 1 using the overflow addition operator (&+). This pushes its binary representation just over the size that a UInt8 can hold, causing it to overflow beyond its bounds, as shown in the diagram below. The value that remains within the bounds of the UInt8 after the overflow addition is 00000000, or zero:

Value Underflow

Numbers can also become too small to fit in their type’s maximum bounds. Here’s an example.

The smallest value that a UInt8 can hold is 0 (which is 00000000 in eight-bit binary form). If you subtract 1 from 00000000 using the overflow subtraction operator, the number will overflow back round to 11111111, or 255 in decimal:

Here’s how that looks in Swift code:

1

2

3

4

var willUnderflow = UInt8.min

//willUnderflow equals 0, which is the smallest value a UInt8 can hold willUnderflow = willUnderflow &- 1

//willUnderflow is now equal to 255

A similar underflow occurs for signed integers. All subtraction for signed integers is performed as straight binary subtraction, with the sign bit included as part of the numbers being subtracted, as described in Bitwise Left and Right Shift Operators. The smallest number that an Int8 can hold is -128, which is 10000000 in binary. Subtracting 1 from this binary number with the overflow operator gives a binary value of 01111111, which toggles the sign bit and gives positive 127, the largest positive value that an Int8 can hold:

Here’s the same thing in Swift code:

1

2

3

4

var signedUnderflow = Int8.min

//signedUnderflow equals -128, which is the smallest value an Int8 can hold signedUnderflow = signedUnderflow &- 1

//signedUnderflow is now equal to 127

The end result of the overflow and underflow behavior described above is that for both signed and unsigned integers, overflow always wraps around from the largest valid integer value back to the smallest, and underflow always wraps around from the smallest value to the largest.

Division by Zero

Dividing a number by zero (i / 0), or trying to calculate remainder by zero (i % 0), causes an error:

1

2

let x = 1

let y = x / 0

However, the overflow versions of these operators (&/ and &%) return a value of zero if you divide by zero:

1

2

3

let x = 1

let y = x &/ 0

// y is equal to 0

Precedence and Associativity

Operator precedence gives some operators higher priority than others; these operators

are calculated first.

Operator associativity defines how operators of the same precedence are grouped together (or associated)—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. Here’s an example. Why does the following expression equal 4?

1

2

2 + 3 * 4 % 5

// this equals 4

Taken strictly from left to right, you might expect this to read as follows:

2 plus 3 equals 5;

5 times 4 equals 20;

20 remainder 5 equals 0

However, the actual answer is 4, not 0. Higher-precedence operators are evaluated before lower-precedence ones. In Swift, as in C, the multiplication operator (*) and the remainder operator (%) have a higher precedence than the addition operator (+). As a result, they are both evaluated before the addition is considered.

However, multiplication and remainder have the same precedence as each other. To work out the exact evaluation order to use, you also need to consider their associativity. Multiplication and remainder 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:

1 2 + ((3 * 4) % 5)

(3 * 4) is 12, so this is equivalent to:

1 2 + (12 % 5)

(12 % 5) is 2, so this is equivalent to:

1 2 + 2

This calculation yields the final answer of 4.

For a complete list of Swift operator precedences and associativity rules, see Expressions.

N O T E

Swift’s operator precedences and associativity rules are simpler and more predictable than those found in C and Objective-C. However, this means that they are not the same as in C-based languages. Be careful to ensure that operator interactions still behave in the way you intend when porting existing code to Swift.

Operator Functions

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 Vector2D structure for a two-dimensional position vector (x, y), followed by a definition of an operator function to add together instances of the Vector2D structure:

1

2

3

4

5

6

struct Vector2D {

var x = 0.0, y = 0.0

}

@infix func + (left: Vector2D, right: Vector2D) -> Vector2D {

return Vector2D(x: left.x + right.x, y: left.y + right.y)

}

The operator function is defined as a global function called +, which takes two input parameters of type Vector2D and returns a single output value, also of type Vector2D. You implement an infix operator by writing the @infix attribute before the func keyword when declaring the operator function.

In this implementation, the input parameters are named left and right to represent the Vector2D instances that will be on the left side and right side of the + operator. The function returns a new Vector2D instance, whose x and y properties are initialized with the sum of the x and y properties from the two Vector2D instances that are added together.

The function is defined globally, rather than as a method on the Vector2D structure, so that it can be used as an infix operator between existing Vector2D instances:

1 let vector = Vector2D(x: 3.0, y: 1.0)

2

3

4

let anotherVector = Vector2D(x: 2.0, y: 4.0)

let combinedVector = vector + anotherVector

// combinedVector is a Vector2D instance with values of (5.0, 5.0)

This example adds together the vectors (3.0, 1.0) and (2.0, 4.0) to make the vector (5.0, 5.0), 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 -a) and postfix operators if they follow their target (such as i++).

You implement a prefix or postfix unary operator by writing the @prefix or @postfix attribute before the func keyword when declaring the operator function:

1

2

3

@prefix func - (vector: Vector2D) -> Vector2D {

return Vector2D(x: -vector.x, y: -vector.y)

}

The example above implements the unary minus operator (-a) for Vector2D instances. The unary minus operator is a prefix operator, and so this function has to be qualified with the @prefix attribute.

For simple numeric values, the unary minus operator converts positive numbers into their negative equivalent and vice versa. The corresponding implementation for Vector2D instances performs this operation on both the x and y properties:

1

2

3

4

5

let positive = Vector2D(x: 3.0, y: 4.0)

let negative = -positive

//negative is a Vector2D instance with values of (-3.0, -4.0) let alsoPositive = -negative

//alsoPositive is a Vector2D instance with values of (3.0, 4.0)

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. Operator functions that implement compound assignment must be qualified with the @assignment attribute. You must also mark a compound assignment operator’s left input parameter as inout, because the parameter’s value will be modified directly from within the operator function.

The example below implements an addition assignment operator function for Vector2D instances:

1

2

3

@assignment func += (inout left: Vector2D, right: Vector2D) {

left = left + right

}

Because an addition operator was defined earlier, you don’t need to reimplement the addition process here. Instead, the addition assignment operator function takes advantage of the existing addition operator function, and uses it to set the left value to be the left value plus the right value:

1

2

3

4

var original = Vector2D(x: 1.0, y: 2.0)

let vectorToAdd = Vector2D(x: 3.0, y: 4.0)

original += vectorToAdd

// original now has values of (4.0, 6.0)

You can combine the @assignment attribute with either the @prefix or @postfix attribute, as in this implementation of the prefix increment operator (++a) for Vector2D instances:

1 @prefix @assignment func ++ (inout vector: Vector2D) -> Vector2D {

2vector += Vector2D(x: 1.0, y: 1.0)

3return vector

4 }

The prefix increment operator function above takes advantage of the addition assignment operator defined earlier. It adds a Vector2D with x and y values of 1.0 to the Vector2D on which it is called, and returns the result:

1

2

3

4

var toIncrement = Vector2D(x: 3.0, y: 4.0)

let afterIncrement = ++toIncrement

//toIncrement now has values of (4.0, 5.0)

//afterIncrement also has values of (4.0, 5.0)

N O T E

It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.

Equivalence Operators

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:

1

2

3

4

5

6

@infix func == (left: Vector2D, right: Vector2D) -> Bool {

return (left.x == right.x) && (left.y == right.y)

}

@infix func != (left: Vector2D, right: Vector2D) -> Bool {

return !(left == right)

}

The above example implements an “equal to” operator (==) to check if two Vector2D

instances have equivalent values. In the context of Vector2D, it makes sense to consider “equal” as meaning “both instances have the same x values and y 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 Vector2D instances are equivalent:

1

2

3

4

5

6

let twoThree = Vector2D(x: 2.0, y: 3.0)

let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)

if twoThree == anotherTwoThree {

println("These two vectors are equivalent.")

}

// prints "These two vectors are equivalent."

Custom Operators

You can declare and implement your own custom operators in addition to the standard operators provided by Swift. Custom operators can be defined only with the characters

/ = - + * % < > ! & | ^ . ~.

New operators are declared at a global level using the operator keyword, and can be

declared as prefix, infix or postfix:

1 operator prefix +++ {}

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 Vector2D instances. For the purposes of this example,

+++ is treated as a new “prefix doubling incrementer” operator. It doubles the x and y values of a Vector2D instance, by adding the vector to itself with the addition assignment operator defined earlier:

1

2

3

4

@prefix @assignment func +++ (inout vector: Vector2D) -> Vector2D {

vector += vector

return vector

}

This implementation of +++ is very similar to the implementation of ++ for Vector2D, except that this operator function adds the vector to itself, rather than adding

Vector2D(1.0, 1.0):

1

2

3

4

var toBeDoubled = Vector2D(x: 1.0, y: 4.0)

let afterDoubling = +++toBeDoubled

//toBeDoubled now has values of (2.0, 8.0)

//afterDoubling also has values of (2.0, 8.0)

Precedence and Associativity for Custom Infix Operators

Custom infix operators can also specify a precedence and an associativity. See Precedence and Associativity for an explanation of how these two characteristics affect an infix operator’s interaction with other infix operators.

The possible values for associativity are left, right, and none. Left-associative operators associate to the left if written next to other left-associative operators of the same precedence. Similarly, right-associative operators associate to the right if written next to other right-associative operators of the same precedence. Non-associative operators cannot be written next to other operators with the same precedence.

The associativity value defaults to none if it is not specified. The precedence value defaults to 100 if it is not specified.

The following example defines a new custom infix operator called +-, with left associativity and a precedence of 140:

1

2

3

4

5

6

7

8

operator infix +- { associativity left precedence 140 } func +- (left: Vector2D, right: Vector2D) -> Vector2D {

return Vector2D(x: left.x + right.x, y: left.y - right.y)

}

let firstVector = Vector2D(x: 1.0, y: 2.0)

let secondVector = Vector2D(x: 3.0, y: 4.0)

let plusMinusVector = firstVector +- secondVector

// plusMinusVector is a Vector2D instance with values of (4.0, -2.0)

This operator adds together the x values of two vectors, and subtracts the y value of the second vector from the first. Because it is in essence an “additive” operator, it has been given the same associativity and precedence values (left and 140) as default additive infix operators such as + and -. For a complete list of the default Swift operator precedence and associativity settings, see Expressions.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]