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

The_Swift_Programming_Language

.pdf
Скачиваний:
20
Добавлен:
18.03.2015
Размер:
4.75 Mб
Скачать

Protocols and Extensions

Use protocol to declare a protocol.

1 protocol ExampleProtocol {

2var simpleDescription: String { get }

3mutating func adjust()

4 }

Classes, enumerations, and structs can all adopt protocols.

1 class SimpleClass: ExampleProtocol {

2var simpleDescription: String = "A very simple class."

3var anotherProperty: Int = 69105

4func adjust() {

5simpleDescription += " Now 100% adjusted."

6}

7

}

8

var a = SimpleClass()

9

a.adjust()

t aDescription = a.simpleDescription

truct SimpleStructure: ExampleProtocol {

var simpleDescription: String = "A simple structure" mutating func adjust() {

simpleDescription += " (adjusted)"

}

ar b = SimpleStructure()

.adjust()

t bDescription = b.simpleDescription

EX P ER I M EN T

Write an enumeration that conforms to this protocol.

Notice the use of the mutating keyword in the declaration of SimpleStructure to mark a method that modifies the structure. The declaration of SimpleClass doesn’t need any of its methods marked as mutating because methods on a class can always modify the class.

Use extension to add functionality to an existing type, such as new methods and computed properties. You can use an extension to add protocol conformance to a type that is declared elsewhere, or even to a type that you imported from a library or framework.

1

2

3

4

5

6

7

8

9

extension Int: ExampleProtocol {

var simpleDescription: String {

return "The number \(self)"

}

mutating func adjust() {

self += 42

}

}

7.simpleDescription

EX P ER I M EN T

Write an extension for the Double type that adds an absoluteValue property.

You can use a protocol name just like any other named type—for example, to create a collection of objects that have different types but that all conform to a single protocol. When you work with values whose type is a protocol type, methods outside the protocol definition are not available.

1

2

3

let protocolValue: ExampleProtocol = a

protocolValue.simpleDescription

// protocolValue.anotherProperty // Uncomment to see the error

Even though the variable protocolValue has a runtime type of SimpleClass, the compiler treats it as the given type of ExampleProtocol. This means that you can’t accidentally access methods or properties that the class implements in addition to its protocol conformance.

Generics

Write a name inside angle brackets to make a generic function or type.

1

2

3

4

5

6

7

8

func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {

var result = ItemType[]()

for i in 0..times {

result += item

}

return result

}

repeat("knock", 4)

You can make generic forms of functions and methods, as well as classes, enumerations, and structures.

1

2

3

4

5

6

7

// Reimplement the Swift standard library's optional type

enum OptionalValue<T> {

case None

case Some(T)

}

var possibleInteger: OptionalValue<Int> = .None

possibleInteger = .Some(100)

Use where after the type name to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.

1

2

3

4

5

6

7

8

func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable,

T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {

for lhsItem in lhs {

for rhsItem in rhs {

if lhsItem == rhsItem {

return true

}

}

}

<T: Equatable>

9 return false

nyCommonElements([1, 2, 3], [3])

EX P ER I M EN T

Modify the anyCommonElements function to make a function that returns an array of the elements that any two sequences have in common.

In the simple cases, you can omit after a colon. Writing

where and simply write the protocol or class name is the same as writing <T where T: Equatable>.

Language Guide

The Basics

Swift is a new programming language for iOS and OS X app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C.

Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers; Double and Float for floating-point values; Bool for Boolean values; and String for textual data. Swift also provides powerful versions of the two primary collection types, Array and Dictionary, as described in Collection Types.

Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent when you work with values that do not need to change.

In addition to familiar types, Swift introduces advanced types not found in Objective-C. These include tuples, which enable you to create and pass around groupings of values. Tuples can return multiple values from a function as a single compound value.

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.

Constants and Variables

Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.

Declaring Constants and Variables

Constants and variables must be declared before they are used. You declare constants with the let keyword and variables with the var keyword. Here’s an example of how constants and variables can be used to track the number of login attempts a user has made:

1

2

let maximumNumberOfLoginAttempts = 10

var currentLoginAttempt = 0

This code can be read as:

“Declare a new constant called maximumNumberOfLoginAttempts, and give it a value of 10. Then, declare a new variable called currentLoginAttempt, and give it an initial value of 0.”

In this example, the maximum number of allowed login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented after each failed login attempt.

You can declare multiple constants or multiple variables on a single line, separated by commas:

1 var x = 0.0, y = 0.0, z = 0.0

N O T E

If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

Type Annotations

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.

This example provides a type annotation for a variable called welcomeMessage, to indicate that the variable can store String values:

1 var welcomeMessage: String

The colon in the declaration means “…of type…,” so the code above can be read as:

“Declare a variable called welcomeMessage that is of type String.”

The phrase “of type String” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.

The welcomeMessage variable can now be set to any string value without error:

1 welcomeMessage = "Hello"

N O T E

It is rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference. In the welcomeMessage example above, no initial value is provided, and so the type of the welcomeMessage variable is specified with a type annotation rather than being inferred from an initial value.

Naming Constants and Variables

You can use almost any character you like for constant and variable names, including Unicode characters:

1

2

3

let π = 3.14159

let = " "

let

= "dogcow"

Constant and variable names cannot contain mathematical symbols, arrows, privateuse (or invalid) Unicode code points, or lineand box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.

Once you’ve declared a constant or variable of a certain type, you can’t redeclare it again with the same name, or change it to store values of a different type. Nor can you change a constant into a variable or a variable into a constant.

N O T E

If you need to give a constant or variable the same name as a reserved Swift keyword, you can do so by surrounding the keyword with back ticks (`) when using it as a name. However, you should avoid using keywords as names unless you have absolutely no choice.

You can change the value of an existing variable to another value of a compatible type. In this example, the value of friendlyWelcome is changed from "Hello!" to "Bonjour!":

1 var friendlyWelcome = "Hello!"

2

3

friendlyWelcome = "Bonjour!"

// friendlyWelcome is now "Bonjour!"

Unlike a variable, the value of a constant cannot be changed once it is set. Attempting to do so is reported as an error when your code is compiled:

1

2

3

let languageName = "Swift"

languageName = "Swift++"

// this is a compile-time error - languageName cannot be changed

Printing Constants and Variables

You can print the current value of a constant or variable with the println function:

1

2

println(friendlyWelcome)

// prints "Bonjour!"

println is a global function that prints a value, followed by a line break, to an appropriate output. If you are working in Xcode, for example, println prints its output in Xcode’s “console” pane. (A second function, print, performs the same task without appending a line break to the end of the value to be printed.)

The println function prints any String value you pass to it:

1

2

println("This is a string")

// prints "This is a string"

The println function can print more complex logging messages, in a similar manner to Cocoa’s NSLog function. These messages can include the current values of constants and variables.

Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis:

1

2

println("The current value of friendlyWelcome is \(friendlyWelcome)")

// prints "The current value of friendlyWelcome is Bonjour!"

N O T E

All options you can use with string interpolation are described in String Interpolation.

Comments

Use comments to include non-executable text in your code, as a note or reminder to yourself. Comments are ignored by the Swift compiler when your code is compiled.

Comments in Swift are very similar to comments in C. Single-line comments begin with two forward-slashes (//):

1 // this is a comment

You can also write multiline comments, which start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/):

1

2

/* this is also a comment,

but written over multiple lines */

Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block:

1

2

3

/* this is the start of the first multiline comment

/* this is the second, nested multiline comment */

this is the end of the first multiline comment */

Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.

Semicolons

Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. Semicolons are required, however, if you want to write multiple separate statements on a single line:

1

2

let cat = " "; println(cat)

// prints " "

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