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

the-swift-rogramming-language

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

​identifier → identifier-head identifier-characters opt ​identifier → ` identifier-head identifier-characters opt ` ​identifier → implicit-parameter-name

​identifier-list → identifier identifier , identifier-list

​identifier-head → Upperor lowercase letter A through Z

​identifier-head → U+00A8, U+00AA, U+00AD, U+00AF, U+00B2–U+00B5, or U+00B7–U+00BA

​identifier-head → U+00BC–U+00BE, U+00C0–U+00D6, U+00D8–U+00F6, or U+00F8–U+00FF

​identifier-head → U+0100–U+02FF, U+0370–U+167F, U+1681–U+180D, or U+180F– U+1DBF

​identifier-head → U+1E00–U+1FFF

​identifier-head → U+200B–U+200D, U+202A–U+202E, U+203F–U+2040, U+2054, or U+2060–U+206F

​identifier-head → U+2070–U+20CF, U+2100–U+218F, U+2460–U+24FF, or U+2776– U+2793

​identifier-head → U+2C00–U+2DFF or U+2E80–U+2FFF

​identifier-head → U+3004–U+3007, U+3021–U+302F, U+3031–U+303F, or U+3040– U+D7FF

​identifier-head → U+F900–U+FD3D, U+FD40–U+FDCF, U+FDF0–U+FE1F, or U+FE30–U+FE44

​identifier-head → U+FE47–U+FFFD

​identifier-head → U+10000–U+1FFFD, U+20000–U+2FFFD, U+30000–U+3FFFD, or U+40000–U+4FFFD

​identifier-head → U+50000–U+5FFFD, U+60000–U+6FFFD, U+70000–U+7FFFD, or U+80000–U+8FFFD

​identifier-head → U+90000–U+9FFFD, U+A0000–U+AFFFD, U+B0000–U+BFFFD, or U+C0000–U+CFFFD

​identifier-head → U+D0000–U+DFFFD or U+E0000–U+EFFFD

​identifier-character → Digit 0 through 9

​identifier-character → U+0300–U+036F, U+1DC0–U+1DFF, U+20D0–U+20FF, or U+FE20–U+FE2F

​identifier-character → identifier-head

​identifier-characters → identifier-character identifier-characters opt

​implicit-parameter-name → $ decimal-digits

Keywords

The following keywords are reserved and may not be used as identifiers, unless they’re escaped with backticks, as described above in Identifiers.

Keywords used in declarations: class, deinit, enum, extension, func, import, init, let, protocol, static, struct, subscript, typealias, and var.

Keywords used in statements: break, case, continue, default, do, else, fallthrough, if, in, for, return, switch, where, and while.

Keywords used in expressions and types: as, dynamicType, is, new, super, self, Self, Type,

__COLUMN__, __FILE__, __FUNCTION__, and __LINE__.

Keywords reserved in particular contexts: associativity, didSet, get, infix, inout, left, mutating,

none, nonmutating, operator, override, postfix, precedence, prefix, right, set, unowned, unowned(safe),

unowned(unsafe), weak and willSet. Outside the context in which they appear in the grammar, they can be used as identifiers.

Literals

A literal is the source code representation of a value of an integer, floating-point number, or string type. The following are examples of literals:

42

// Integer literal

3.14159 // Floating-point literal

"Hello, world!" // String literal

G R A M M A R O F A L I T E R A L

​literal → integer-literal floating-point-literal string-literal

Integer Literals

Integer literals represent integer values of unspecified precision. By default, integer literals are expressed in decimal; you can specify an alternate base using a prefix. Binary literals begin with 0b, octal literals begin with 0o, and hexadecimal literals begin with 0x.

Decimal literals contain the digits 0 through 9. Binary literals contain 0 and 1, octal literals

contain 0 through 7, and hexadecimal literals contain 0 through 9 as well as A through F in upperor lowercase.

Negative integers literals are expressed by prepending a minus sign (-) to an integer literal, as in -42.

Underscores (_) are allowed between digits for readability, but are ignored and therefore don’t affect the value of the literal. Integer literals can begin with leading zeros (0), but are likewise ignored and don’t affect the base or value of the literal.

Unless otherwise specified, the default type of an integer literal is the Swift standard library type Int. The Swift standard library also defines types for various sizes of signed and unsigned integers, as described in Integers.

G R A M M A R O F A N I N T E G E R L I T E R A L

​integer-literal → binary-literal ​integer-literal → octal-literal ​integer-literal → decimal-literal ​integer-literal → hexadecimal-literal

​binary-literal → 0b binary-digit binary-literal-characters opt ​binary-digit → Digit 0 or 1

​binary-literal-character → binary-digit _

​binary-literal-characters → binary-literal-character binary-literal-characters opt

​octal-literal → 0o octal-digit octal-literal-characters opt ​octal-digit → Digit 0 through 7

​octal-literal-character → octal-digit _

​octal-literal-characters → octal-literal-character octal-literal-characters opt

​decimal-literal → decimal-digit decimal-literal-characters opt ​decimal-digit → Digit 0 through 9

​decimal-digits → decimal-digit decimal-digits opt ​decimal-literal-character → decimal-digit _

​decimal-literal-characters → decimal-literal-character decimal-literal-characters opt

​hexadecimal-literal → 0x hexadecimal-digit hexadecimal-literal-characters opt ​hexadecimal-digit → Digit 0 through 9, a through f, or A through F ​hexadecimal-literal-character → hexadecimal-digit _ ​hexadecimal-literal-characters → hexadecimal-literal-character hexadecimal-literal-

characters opt

3.75.

Floating-Point Literals

Floating-point literals represent floating-point values of unspecified precision.

By default, floating-point literals are expressed in decimal (with no prefix), but they can also be expressed in hexadecimal (with a 0x prefix).

Decimal floating-point literals consist of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both. The decimal fraction consists of a decimal point (.) followed by a sequence of decimal digits. The exponent consists of an upperor lowercase e prefix followed by sequence of decimal digits that indicates what power of 10

the value preceding the e is multiplied by. For example, 1.25e2 represents 1.25

102,

which evaluates to 125.0. Similarly, 1.25e-2 represents 1.25

10-2, which evaluates to

0.0125.

 

 

Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent. The hexadecimal fraction consists of a decimal point followed by a sequence of hexadecimal digits. The exponent consists of an upperor lowercase p prefix followed by sequence of decimal digits that indicates what power of 2 the value preceding the p is multiplied by. For example, 0xFp2 represents 15 22, which evaluates to 60. Similarly, 0xFp-2 represents 15 2-2, which evaluates to

Unlike with integer literals, negative floating-point numbers are expressed by applying the unary minus operator (-) to a floating-point literal, as in -42.0. The result is an expression, not a floating-point integer literal.

Underscores (_) are allowed between digits for readability, but are ignored and therefore don’t affect the value of the literal. Floating-point literals can begin with leading zeros (0), but are likewise ignored and don’t affect the base or value of the literal.

Unless otherwise specified, the default type of a floating-point literal is the Swift standard library type Double, which represents a 64-bit floating-point number. The Swift standard library also defines a Float type, which represents a 32-bit floating-point number.

G R A M M A R O F A F L O A T I N G - P O I N T L I T E R A L

​floating-point-literal → decimal-literal decimal-fractionopt decimal-exponent opt ​floating-point-literal → hexadecimal-literal hexadecimal-fractionopt hexadecimal-

exponent

​decimal-fraction → . decimal-literal

​decimal-exponent → floating-point-e signopt decimal-literal ​hexadecimal-fraction → . hexadecimal-literal opt

​hexadecimal-exponent → floating-point-p signopt hexadecimal-literal

​floating-point-e → ​floating-point-p → ​sign → + -

e E

p P

String Literals

A string literal is a sequence of characters surrounded by double quotes, with the following form:

" characters "

String literals cannot contain an unescaped double quote ("), an unescaped backslash (\), a carriage return, or a line feed.

Special characters can be included in string literals using the following escape sequences:

Null Character (\0)

Backslash (\\)

Horizontal Tab (\t)

Line Feed (\n)

Carriage Return (\r)

Double Quote (\")

Single Quote (\')

Characters can also be expressed by \x followed by two hexadecimal digits, \u followed by four hexadecimal digits, or \U followed by eight hexadecimal digits. The digits in these escape sequences identify a Unicode codepoint.

The value of an expression can be inserted into a string literal by placing the expression in parentheses after a backslash (\). The interpolated expression must not contain an unescaped double quote ("), an unescaped backslash (\), a carriage return, or a line feed. The expression must evaluate to a value of a type that the String class has an initializer for.

For example, all the following string literals have the same value:

"1 2 3"

"1 2 \(3)"

"1 2 \(1 + 2)"

var x = 3; "1 2 \(x)"

The default type of a string literal is String. The characters that make up a string are of type Character. For more information about the String and Character types, see Strings and Characters.

G R A M M A R O F A S T R I N G L I T E R A L

​string-literal → " quoted-text "

​quoted-text → quoted-text-item quoted-text opt ​quoted-text-item → escaped-character ​quoted-text-item → \( expression )

​quoted-text-item → Any Unicode extended grapheme cluster except " , \ , U+000A, or U+000D

​escaped-character → \0 \\ \t \n \r \" \' ​escaped-character → \x hexadecimal-digit hexadecimal-digit

​escaped-character → \u hexadecimal-digit hexadecimal-digit hexadecimaldigit hexadecimal-digit

​escaped-character → \U hexadecimal-digit hexadecimal-digit hexadecimaldigit hexadecimal-digit hexadecimal-digit hexadecimal-digit hexadecimaldigit hexadecimal-digit

Operators

The Swift standard library defines a number of operators for your use, many of which are discussed in Basic Operators and Advanced Operators. The present section describes which characters can be used as operators.

Operators are made up of one or more of the following characters: /, =, -, +, !, *, %, <, >, &, |, ^, ~, and .. That said, the tokens =, ->, //, /*, */, ., and the unary prefix operator & are reserved. These tokens can’t be overloaded, nor can they be used to define custom operators.

The whitespace around an operator is used to determine whether an operator is used as a prefix operator, a postfix operator, or a binary operator. This behavior is summarized in the following rules:

If an operator has whitespace around both sides or around neither side, it is treated as a binary operator. As an example, the + operator in a+b and a + b is treated as a binary operator.

If an operator has whitespace on the left side only, it is treated as a prefix unary operator. As an example, the ++ operator in a ++b is treated as a prefix unary operator.

If an operator has whitespace on the right side only, it is treated as a postfix unary operator. As an example, the ++ operator in a++ b is treated as a postfix unary operator.

If an operator has no whitespace on the left but is followed immediately by a dot (.), it is treated as a postfix unary operator. As an example, the ++ operator in a++.b is treated as a postfix unary operator (a++ . b rather than a ++ .b).

For the purposes of these rules, the characters (, [, and { before an operator, the characters ), ], and } after an operator, and the characters ,, ;, and : are also considered whitespace.

There is one caveat to the rules above. If the ! or ? operator has no whitespace on the left, it is treated as a postfix operator, regardless of whether it has whitespace on the right. To use the ? operator as syntactic sugar for the Optional type, it must not have whitespace on the left. To use it in the conditional (? :) operator, it must have whitespace around both sides.

In certain constructs, operators with a leading < or > may be split into two or more tokens. The remainder is treated the same way and may be split again. As a result, there is no need to use whitespace to disambiguate between the closing > characters in constructs like Dictionary<String, Array<Int>>. In this example, the closing > characters are not treated as a single token that may then be misinterpreted as a bit shift >> operator.

To learn how to define new, custom operators, see Custom Operators and Operator Declaration. To learn how to overload existing operators, see Operator Functions.

G R A M M A R O F O P E R A T O R S

​operator → operator-character operatoropt ​operator-character → / = - + ! * % < > & | ^ ~ .

​binary-operator → operator ​prefix-operator → operator ​postfix-operator → operator

Types

In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it is defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass. In addition to user-defined named types, the Swift standard library defines many commonly used named types, including those that represent arrays, dictionaries, and optional values.

Data types that are normally considered basic or primitive in other languages—such as types that represent numbers, characters, and strings—are actually named types, defined and implemented in the Swift standard library using structures. Because they are named types, you can extend their behavior to suit the needs of your program, using an extension declaration, discussed in Extensions and Extension Declaration.

A compound type is a type without a name, defined in the Swift language itself. There are two compound types: function types and tuple types. A compound type may contain named types and other compound types. For instance, the tuple type (Int, (Int, Int)) contains two elements: The first is the named type Int, and the second is another compound type

(Int, Int).

This chapter discusses the types defined in the Swift language itself and describes the type inference behavior of Swift.

G R A M M A R O F A T Y P E

​type → array-type function-type type-identifier tuple-type optional-type implicitly-unwrapped-optional-type protocol-composition-type metatype-type

Type Annotation

A type annotation explicitly specifies the type of a variable or expression. Type annotations begin with a colon (:) and end with a type, as the following examples show:

let someTuple: (Double, Double) = (3.14159, 2.71828)

func someFunction(a: Int) { /* ... */ }

In the first example, the expression someTuple is specified to have the tuple type (Double, Double). In the second example, the parameter a to the function someFunction is specified to

have the type Int.

Type annotations can contain an optional list of type attributes before the type.

G R A M M A R O F A T Y P E A N N O T A T I O N

​type-annotation → : attributes opt type

Type Identifier

A type identifier refers to either a named type or a type alias of a named or compound type.

Most of the time, a type identifier directly refers to a named type with the same name as the identifier. For example, Int is a type identifier that directly refers to the named type Int, and the type identifier Dictionary<String, Int> directly refers to the named type

Dictionary<String, Int>.

There are two cases in which a type identifier does not refer to a type with the same name. In the first case, a type identifier refers to a type alias of a named or compound type. For instance, in the example below, the use of Point in the type annotation refers to the tuple type (Int, Int).

typealias Point = (Int, Int) let origin: Point = (0, 0)

In the second case, a type identifier uses dot (.) syntax to refer to named types declared in other modules or nested within other types. For example, the type identifier in the following code references the named type MyType that is declared in the ExampleModule module.

var someValue: ExampleModule.MyType

G R A M M A R O F A T Y P E I D E N T I F I E R

​type-identifier → type-name generic-argument-clause opt type-name generic- argument-clause opt . type-identifier

​type-name → identifier

Tuple Type

auto_closure

A tuple type is a comma-separated list of zero or more types, enclosed in parentheses.

You can use a tuple type as the return type of a function to enable the function to return a single tuple containing multiple values. You can also name the elements of a tuple type and use those names to refer to the values of the individual elements. An element name consists of an identifier followed immediately by a colon (:). For an example that demonstrates both of these features, see Functions with Multiple Return Values.

Void is a typealias for the the empty tuple type, (). If there is only one element inside the parentheses, the type is simply the type of that element. For example, the type of (Int) is Int, not (Int). As a result, you can label a tuple element only when the tuple type has two or more elements.

G R A M M A R O F A T U P L E T Y P E

​tuple-type → ( tuple-type-body opt ) ​tuple-type-body → tuple-type-element-list ... opt

​tuple-type-element-list → tuple-type-element tuple-type-element , tuple-type- element-list

​tuple-type-element → attributes opt inout opt type inout opt element-name typeannotation

​element-name → identifier

Function Type

A function type represents the type of a function, method, or closure and consists of a parameter and return type separated by an arrow (->):

parameter type -> return type

Because the parameter type and the return type can be a tuple type, function types support functions and methods that take multiple paramaters and return multiple values.

You can apply the auto_closure attribute to a function type that has a parameter type of () and that returns the type of an expression (see Type Attributes). An autoclosure function captures an implicit closure over the specified expression, instead of the expression itself. The following example uses the attribute in defining a very simple assert function:

func simpleAssert(condition: @auto_closure () -> Bool, message: String) {

if !condition() {

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