iOS 10 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 3rd Edition Matt Neuburg instant download
iOS 10 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 3rd Edition Matt Neuburg instant download
https://textbookfull.com/product/ios-10-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-3rd-edition-matt-neuburg/
https://textbookfull.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg/
https://textbookfull.com/product/ios-11-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-4th-edition-matt-neuburg/
https://textbookfull.com/product/ios-13-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-1st-edition-matt-neuburg/
https://textbookfull.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-
neuburg-2/
iOS 12 Programming Fundamentals with Swift Swift Xcode
and Cocoa Basics 5th Edition Matt Neuburg
https://textbookfull.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-
neuburg-3/
https://textbookfull.com/product/ios-14-programming-fundamentals-
with-swift-covers-ios-14-xcode-12-and-swift-5-3-7th-edition-matt-
neuburg/
https://textbookfull.com/product/programming-ios-14-11th-edition-
matt-neuburg/
https://textbookfull.com/product/learn-ios-11-programming-with-
swift-4-craig-clayton/
https://textbookfull.com/product/programming-ios-10-dive-deep-
into-views-view-controllers-and-frameworks-seventh-edition-matt-
neuburg/
Xc
Co e 8
od
ve , a
rs nd
i O Sw
S 1 if
0, t 3
iOS 10
Programming
Fundamentals
with Swift
SWIFT, XCODE, AND COCOA BASICS
Matt Neuburg
THIRD EDITION
iOS 10 Programming
Fundamentals with Swift
Swift, Xcode, and Cocoa Basics
Matt Neuburg
Boston
iOS 10 Programming Fundamentals with Swift, Third Edition
by Matt Neuburg
Copyright © 2017 Matt Neuburg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected].
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 10 Programming Fundamentals
with Swift, the image of a harp seal, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
ISBN: 978-1-491-97007-2
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Part I. Language
1. The Architecture of Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Ground of Being 3
Everything Is an Object? 5
Three Flavors of Object Type 6
Variables 6
Functions 8
The Structure of a Swift File 9
Scope and Lifetime 11
Object Members 12
Namespaces 13
Modules 14
Instances 15
Why Instances? 17
self 19
Privacy 20
Design 22
Object Types and APIs 23
Instance Creation, Scope, and Lifetime 25
Summary and Conclusion 26
2. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Function Parameters and Return Value 27
Void Return Type and Parameters 31
Function Signature 32
iii
External Parameter Names 32
Overloading 34
Default Parameter Values 35
Variadic Parameters 36
Ignored Parameters 36
Modifiable Parameters 37
Function In Function 41
Recursion 43
Function As Value 43
Anonymous Functions 46
Define-and-Call 52
Closures 53
How Closures Improve Code 54
Function Returning Function 56
Closure Setting a Captured Variable 58
Closure Preserving Its Captured Environment 59
Escaping Closures 60
Curried Functions 61
Function References and Selectors 62
Function Reference Scope 65
Selectors 66
iv | Table of Contents
Methods 128
Subscripts 130
Nested Object Types 132
Instance References 133
Enums 135
Raw Values 137
Associated Values 138
Enum Initializers 139
Enum Properties 140
Enum Methods 141
Why Enums? 142
Structs 143
Struct Initializers, Properties, and Methods 144
Struct As Namespace 145
Classes 146
Value Types and Reference Types 146
Subclass and Superclass 151
Class Initializers 156
Class Deinitializer 164
Class Properties and Methods 164
Polymorphism 166
Casting 169
Type Reference 174
Protocols 179
Why Protocols? 181
Protocol Type Testing and Casting 183
Declaring a Protocol 183
Optional Protocol Members 185
Class Protocol 186
Implicitly Required Initializers 187
Literal Convertibles 189
Generics 190
Generic Declarations 192
Type Constraints 194
Explicit Specialization 196
Associated Type Chains 197
Additional Constraints 200
Extensions 203
Extending Object Types 203
Extending Protocols 206
Extending Generics 209
Umbrella Types 210
Table of Contents | v
Any 211
AnyObject 212
AnyClass 215
Collection Types 216
Array 216
Dictionary 230
Set 235
vi | Table of Contents
Property List Settings 319
Nib Files 320
Additional Resources 321
Code Files and the App Launch Process 324
Frameworks and SDKs 329
Renaming Parts of a Project 331
8. Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
The Documentation Window 367
Class Documentation Pages 369
Quick Help 372
Symbols 374
Header Files 375
Sample Code 376
Internet Resources 376
Table of Contents | ix
Notifications 492
Receiving a Notification 493
Unregistering 495
Posting a Notification 496
Timer 497
Delegation 498
Cocoa Delegation 499
Implementing Delegation 500
Data Sources 502
Actions 503
The Responder Chain 506
Deferring Responsibility 507
Nil-Targeted Actions 508
Key–Value Observing 509
Swamped by Events 513
Delayed Performance 516
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
x | Table of Contents
Preface
On June 2, 2014, Apple’s WWDC keynote address ended with a shocking announce‐
ment: “We have a new programming language.” This came as a huge surprise to the
developer community, which was accustomed to Objective-C, warts and all, and
doubted that Apple could ever possibly relieve them from the weight of its venerable
legacy. The developer community, it appeared, had been wrong.
Having picked themselves up off the floor, developers immediately began to examine
this new language — Swift — studying it, critiquing it, and deciding whether to use it.
My own first move was to translate all my existing iOS apps into Swift; this was
enough to convince me that, for all its faults, Swift deserved to be adopted by new
students of iOS programming, and that my books, therefore, should henceforth
assume that readers are using Swift.
The Swift language is designed from the ground up with these salient features:
Object-orientation
Swift is a modern, object-oriented language. It is purely object-oriented: “Every‐
thing is an object.”
Clarity
Swift is easy to read and easy to write. Its syntax is clear, consistent, and explicit,
with few hidden shortcuts and minimal syntactic trickery.
Safety
Swift enforces strong typing to ensure that it knows, and that you know, what the
type of every object reference is at every moment.
Economy
Swift is a fairly small language, providing some basic types and functionalities
and no more. The rest must be provided by your code, or by libraries of code that
you use — such as Cocoa.
xi
Memory management
Swift manages memory automatically. You will rarely have to concern yourself
with memory management.
Cocoa compatibility
The Cocoa APIs are written in C and Objective-C. Swift is explicitly designed to
interface with most of the Cocoa APIs.
These features make Swift an excellent language for learning to program iOS.
The alternative, Objective-C, still exists, and you can use it if you like. Indeed, it is
easy to write an app that includes both Swift code and Objective-C code; and you may
have reason to do so. Objective-C, however, lacks the very advantages that Swift
offers. Objective-C agglomerates object-oriented features onto C. It is therefore only
partially object-oriented; it has both objects and scalar data types, and its objects have
to be slotted into one particular C data type (pointers). Its syntax can be difficult and
tricky; reading and writing nested method calls can make one’s eyes glaze over, and it
invites hacky habits such as implicit nil-testing. Its type checking can be and fre‐
quently is turned off, resulting in programmer errors where a message is sent to the
wrong type of object and the program crashes. It uses manual memory management;
the recent introduction of ARC (automatic reference counting) has alleviated some of
the programmer tedium and has greatly reduced the likelihood of programmer error,
but errors are still possible, and memory management ultimately remains manual.
Recent revisions and additions to Objective-C — ARC, synthesis and autosynthesis,
improved literal array and dictionary syntax, blocks — have made it easier and more
convenient, but such patches have also made the language even larger and possibly
even more confusing. Because Objective-C must encompass C, there are limits to
how far it can be extended and revised. Swift, on the other hand, is a clean start. If
you were to dream of completely revising Objective-C to create a better Objective-C,
Swift might be what you would dream of. It puts a modern, rational front end
between you and the Cocoa Objective-C APIs.
Therefore, Swift is the programming language used throughout this book. Neverthe‐
less, the reader will also need some awareness of Objective-C (including C). The
Foundation and Cocoa APIs, the built-in commands with which your code must
interact in order to make anything happen on an iOS device, are still written in C and
Objective-C. In order to interact with them, you have to know what those languages
would expect. For example, in order to pass a Swift array where an NSArray is
expected, you need to know what constitutes an object acceptable as an element of an
Objective-C NSArray.
Therefore, in this edition, although I do not attempt to teach Objective-C, I do
describe it in enough detail to allow you to read it when you encounter it in the docu‐
mentation and on the Internet, and I occasionally show some Objective-C code.
xii | Preface
Part III, on Cocoa, is really all about learning to think the way Objective-C thinks —
because the structure and behavior of the Cocoa APIs are fundamentally based on
Objective-C. And the book ends with an appendix that details how Swift and
Objective-C communicate with one another, as well as explaining how your app can
be written partly in Swift and partly in Objective-C.
• Part I introduces the Swift language, from the ground up — I do not assume that
you know any other programming languages. My way of teaching Swift is differ‐
ent from other treatments, such as Apple’s; it is systematic and Euclidean, with
pedagogical building blocks piled on one another in what I regard as the most
helpful order. At the same time, I have tried to confine myself to the essentials.
Swift is not a big language, but it has some subtle and unusual corners. You don’t
need to dive deep into all of these, and my discussion will leave many of them
unexplored. You will probably never encounter them, and if you do, you will
have entered an advanced Swift world outside the scope of this discussion. To
give an obvious example, readers may be surprised to find that I never mention
Swift playgrounds or the REPL. My focus here is real-life iOS programming, and
my explanation of Swift therefore concentrates on those common, practical
Preface | xiii
aspects of the language that, in my experience, actually come into play in the
course of programming iOS.
• Part II turns to Xcode, the world in which all iOS programming ultimately takes
place. It explains what an Xcode project is and how it is transformed into an app,
and how to work comfortably and nimbly with Xcode to consult the documenta‐
tion and to write, navigate, and debug code, as well as how to bring your app
through the subsequent stages of running on a device and submission to the App
Store. There is also a very important chapter on nibs and the nib editor (Interface
Builder), including outlets and actions as well as the mechanics of nib loading;
however, such specialized topics as autolayout constraints in the nib are post‐
poned to the other book.
• Part III introduces the Cocoa Touch framework. When you program for iOS, you
take advantage of a suite of frameworks provided by Apple. These frameworks,
taken together, constitute Cocoa; the brand of Cocoa that provides the API for
programming iOS is Cocoa Touch. Your code will ultimately be almost entirely
about communicating with Cocoa. The Cocoa Touch frameworks provide the
underlying functionality that any iOS app needs to have. But to use a framework,
you have to think the way the framework thinks, put your code where the frame‐
work expects it, and fulfill many obligations imposed on you by the framework.
To make things even more interesting, Cocoa uses Objective-C, while you’ll be
using Swift: you need to know how your Swift code will interface with Cocoa’s
features and behaviors. Cocoa provides important foundational classes and adds
linguistic and architectural devices such as categories, protocols, delegation, and
notifications, as well as the pervasive responsibilities of memory management.
Key–value coding and key–value observing are also discussed here.
The reader of this book will thus get a thorough grounding in the fundamental
knowledge and techniques that any good iOS programmer needs. The book itself
doesn’t show how to write any particularly interesting iOS apps, but it does constantly
use my own real apps and real programming situations to illustrate and motivate its
explanations. And then you’ll be ready for Programming iOS 10, of course!
Versions
This book is geared to Swift 3, iOS 10, and Xcode 8.
In general, only very minimal attention is given to earlier versions of iOS and Xcode.
It is not my intention to embrace in this book any detailed knowledge about earlier
versions of the software, which is, after all, readily and compendiously available in my
earlier books. The book does contain, nevertheless, a few words of advice about back‐
ward compatibility (especially in Chapter 9).
xiv | Preface
The Swift language included with Xcode 8, Swift 3, has changed very significantly
from its predecessor, Swift 2. A few important basic syntax changes were foreshad‐
owed in Swift 2.2 and Swift 2.3, but Swift 3 adds many more, plus “renamification”
has changed the names of many standard library and Cocoa methods, along with the
new Foundation “overlay” that removes the “NS” prefix from certain type names.
Fortunately, if you have existing Swift 2 code, Xcode 8 comes with a migrator that will
update your Swift 2 code to Swift 3 in a remarkably intelligent fashion. This book,
conversely, is totally incompatible with Swift 2 and doesn’t discuss it; for the most
part, I behave as if Swift 2 never existed. I do call out a few particularly noteworthy
Swift 3 innovations, but by no means all of them.
In this edition, I have dropped my earlier convention of referring to Cocoa methods
by their Objective-C name, because “renamification” has made it impossible to
deduce the Swift 3 name of an Objective-C method. Instead, I give the name in Swift,
as a function reference (as described in Chapter 2) — that is, the name plus the
parameter labels followed by colon in parentheses. Now and then, if a method is
already under discussion and there is no ambiguity, I’ll use the bare name. (In a few
places, such as Appendix A, where the Objective-C language is explicitly under dis‐
cussion, I naturally do still use Objective-C method names.)
Please bear in mind that Apple continues to make adjustments to the Swift language.
I have tried to keep my code up-to-date right up to the moment when the manuscript
left my hands; but if, at some future time, a new version of Xcode is released along
with a new version of Swift, some of the code in this book, and even some informa‐
tion about Swift itself, might be slightly incorrect. Please make allowances, and be
prepared to compensate.
Screenshots of Xcode were taken using Xcode 8 under OS X 10.11 El Capitan. I have
not upgraded my machine to macOS 10.12 Sierra, because at the time of this writing
it was too new to be trusted with mission-critical work. If you are braver than I am
and are running Sierra, your interface may naturally look very slightly different from
the screenshots, but this difference will be minimal and shouldn’t cause any confu‐
sion.
Acknowledgments
My thanks go first and foremost to the people at O’Reilly Media who have made writ‐
ing a book so delightfully easy: Rachel Roumeliotis, Sarah Schneider, Kristen Brown,
Dan Fauxsmith, Adam Witwer, and Sanders Kleinfeld come particularly to mind.
And let’s not forget my first and long-standing editor, Brian Jepson, whose influence
is present throughout.
Preface | xv
As in the past, I have been greatly aided by some fantastic software, whose excellences
I have appreciated at every moment of the process of writing this book. I should like
to mention, in particular:
• git (http://git-scm.com)
• SourceTree (http://www.sourcetreeapp.com)
• TextMate (http://macromates.com)
• AsciiDoc (http://www.methods.co.nz/asciidoc)
• Asciidoctor (http://asciidoctor.org)
• BBEdit (http://barebones.com/products/bbedit/)
• EasyFind (http://www.devontechnologies.com/products/freeware.html)
• Snapz Pro X (http://www.ambrosiasw.com)
• GraphicConverter (http://www.lemkesoft.com)
• OmniGraffle (http://www.omnigroup.com)
The book was typed and edited entirely on my faithful Unicomp Model M keyboard
(http://pckeyboard.com), without which I could never have done so much writing over
so long a period so painlessly. For more about my physical work environment, see
http://matt.neuburg.usesthis.com.
xvi | Preface
The widespread eagerness to program iOS, however, though delightful on the one
hand, has also fostered a certain tendency to try to run without first learning to walk.
iOS gives the programmer mighty powers that can seem as limitless as imagination
itself, but it also has fundamentals. I often see questions online from programmers
who are evidently deep into the creation of some interesting app, but who are stymied
in a way that reveals quite clearly that they are unfamiliar with the basics of the very
world in which they are so happily cavorting.
It is this state of affairs that has motivated me to write this book, which is intended to
ground the reader in the fundamentals of iOS. I love Cocoa and have long wished to
write about it, but it is iOS and its popularity that has given me a proximate excuse to
do so. Here I have attempted to marshal and expound, in what I hope is a pedagogi‐
cally helpful and instructive yet ruthlessly Euclidean and logical order, the principles
and elements on which sound iOS programming rests. My hope, as with my previous
books, is that you will both read this book cover to cover (learning something new
often enough to keep you turning the pages) and keep it by you as a handy reference.
This book is not intended to disparage Apple’s own documentation and example
projects. They are wonderful resources and have become more wonderful as time
goes on. I have depended heavily on them in the preparation of this book. But I also
find that they don’t fulfill the same function as a reasoned, ordered presentation of
the facts. The online documentation must make assumptions as to how much you
already know; it can’t guarantee that you’ll approach it in a given order. And online
documentation is more suitable to reference than to instruction. A fully written
example, no matter how well commented, is difficult to follow; it demonstrates, but it
does not teach.
A book, on the other hand, has numbered chapters and sequential pages; I can
assume you know views before you know view controllers for the simple reason that
Part I precedes Part II. And along with facts, I also bring to the table a degree of expe‐
rience, which I try to communicate to you. Throughout this book you’ll find me
referring to “common beginner mistakes”; in most cases, these are mistakes that I
have made myself, in addition to seeing others make them. I try to tell you what the
pitfalls are because I assume that, in the course of things, you will otherwise fall into
them just as naturally as I did as I was learning. You’ll also see me construct many
examples piece by piece or extract and explain just one tiny portion of a larger app. It
is not a massive finished program that teaches programming, but an exposition of the
thought process that developed that program. It is this thought process, more than
anything else, that I hope you will gain from reading this book.
Preface | xvii
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, databases, data types, environment
variables, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
xviii | Preface
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at [email protected].
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/ios10-prog-fundamentals.
To comment or ask technical questions about this book, send email to bookques‐
[email protected].
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Preface | xix
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
xx | Preface
PART I
Language
This part of the book teaches the Swift language, from the ground up. The descrip‐
tion is rigorous and orderly. Here you’ll become sufficiently conversant with Swift to
be comfortable with it, so that you can proceed to the practical business of actual pro‐
gramming.
• Chapter 1 surveys the structure of a Swift program, both physically and concep‐
tually. You’ll learn how Swift code files are organized, and you’ll be introduced to
the most important underlying concepts of the object-oriented Swift language:
variables and functions, scopes and namespaces, object types and their instances.
• Chapter 2 explores Swift functions. We start with the basics of how functions are
declared and called; then we discuss parameters — external parameter names,
default parameters, and variadic parameters. Then we dive deep into the power
of Swift functions, with an explanation of functions inside functions, functions as
first-class values, anonymous functions, functions as closures, curried functions,
and function references and selectors.
• Chapter 3 starts with Swift variables — their scope and lifetime, and how they are
declared and initialized, along with features such as computed variables and set‐
ter observers. Then some important built-in Swift types are introduced, includ‐
ing Booleans, numbers, strings, ranges, tuples, and Optionals.
• Chapter 4 is all about Swift object types — classes, structs, and enums. It explains
how these three object types work, and how you declare, instantiate, and use
them. Then it proceeds to polymorphism and casting, protocols, generics, and
extensions. The chapter concludes with a discussion of Swift’s umbrella types,
such as Any and AnyObject, and collection types — Array, Dictionary, and Set
(including option sets).
• Chapter 5 is a miscellany. We start with Swift’s flow control structures for branch‐
ing, looping, and jumping, including error handling. Then I’ll explain how to
create your own Swift operators. The chapter concludes by describing Swift
access control (privacy), introspection (reflection), and memory management.
CHAPTER 1
The Architecture of Swift
It will be useful at the outset for you to have a general sense of how the Swift language
is constructed and what a Swift-based iOS program looks like. This chapter will sur‐
vey the overall architecture and nature of the Swift language. Subsequent chapters
will fill in the details.
Ground of Being
A complete Swift command is a statement. A Swift text file consists of multiple lines
of text. Line breaks are meaningful. The typical layout of a program is one statement,
one line:
print("hello")
print("world")
3
print(
"world")
Comments are everything after two slashes in a line (so-called C++-style comments):
print("world") // this is a comment, so Swift ignores it
You can also enclose comments in /*...*/, as in C. Unlike C, C-style comments can
be nested.
Many constructs in Swift use curly braces as delimiters:
class Dog {
func bark() {
print("woof")
}
}
By convention, the contents of curly braces are preceded and followed by line breaks
and are indented for clarity, as shown in the preceding code. Xcode will help impose
this convention, but the truth is that Swift doesn’t care, and layouts like this are legal
(and are sometimes more convenient):
class Dog { func bark() { print("woof") }}
Swift is a compiled language. This means that your code must build — passing
through the compiler and being turned from text into some lower-level form that a
computer can understand — before it can run and actually do the things it says to do.
The Swift compiler is very strict; in the course of writing a program, you will often try
to build and run, only to discover that you can’t even build in the first place, because
the compiler will flag some error, which you will have to fix if you want the code to
run. Less often, the compiler will let you off with a warning; the code can run, but in
general you should take warnings seriously and fix whatever they are telling you
about. The strictness of the compiler is one of Swift’s greatest strengths, and provides
your code with a large measure of audited correctness even before it ever starts run‐
ning.
The Swift compiler’s error and warning messages range from the insightful to the
obtuse to the downright misleading. You will often know that something is wrong
with a line of code, but the Swift compiler will not be telling you clearly exactly
what is wrong or even where in the line to focus your attention. My advice in
these situations is to pull the line apart into several lines of simpler code until you
reach a point where you can guess what the issue is. Try to love the compiler
despite the occasional unhelpful nature of its messages. Remember, it knows
more than you do, even if it is sometimes rather inarticulate about its knowledge.
But it is surprising to find that 1 can be followed by a dot and a message. This is legal
and meaningful in Swift (don’t worry about what it actually means):
let s = 1.description
But we can go further. Return to that innocent-looking 1 + 2 from our earlier code.
It turns out that this is actually a kind of syntactic trickery, a convenient way of
expressing and hiding what’s really going on. Just as 1 is actually an object, + is
actually a message; but it’s a message with special syntax (operator syntax). In Swift,
every noun is an object, and every verb is a message.
Perhaps the ultimate acid test for whether something is an object in Swift is whether
you can modify it. An object type can be extended in Swift, meaning that you can
define your own messages on that type. For example, you can’t normally send the say-
Hello message to a number. But you can change a number type so that you can:
extension Int {
func sayHello() {
print("Hello, I'm \(self)")
}
}
1.sayHello() // outputs: "Hello, I'm 1"
Everything Is an Object? | 5
In Swift, then, 1 is an object. In some languages, such as Objective-C, it clearly is not;
it is a “primitive” or scalar built-in data type. So the distinction being drawn here is
between object types on the one hand and scalars on the other. In Swift, there are no
scalars; all types are ultimately object types. That’s what “everything is an object”
really means.
Variables
A variable is a name for an object. Technically, it refers to an object; it is an object
reference. Nontechnically, you can think of it as a shoebox into which an object is
placed. The object may undergo changes, or it may be replaced inside the shoebox by
another object, but the name has an integrity all its own. The object to which the vari‐
able refers is the variable’s value.
In Swift, no variable comes implicitly into existence; all variables must be declared. If
you need a name for something, you must say “I’m creating a name.” You do this with
one of two keywords: let or var. In Swift, declaration is usually accompanied by ini‐
tialization — you use an equal sign to give the variable a value immediately, as part of
the declaration. These are both variable declarations (and initializations):
let one = 1
var two = 2
The last line of that code uses both the name one and the name two declared in the
first two lines: the name one, on the right side of the equal sign, is used merely to refer
to the value inside the shoebox one (namely 1); but the name two, on the left side of
the equal sign, is used to replace the value inside the shoebox two. A statement like
that, with a variable name on the left side of an equal sign, is called an assignment,
and the equal sign is the assignment operator. The equal sign is not an assertion of
equality, as it might be in an algebraic formula; it is a command. It means: “Get the
value of what’s on the right side of me, and use it to replace the value of what’s on the
left side of me.”
The two kinds of variable declaration differ in that a name declared with let cannot
have its value replaced. A variable declared with let is a constant; its value is assigned
once and stays. This won’t even compile:
let one = 1
var two = 2
one = two // compile error
It is always possible to declare a name with var to give yourself the most flexibility,
but if you know you’re never going to replace the initial value of a variable, it’s better
to use let, as this permits Swift to behave more efficiently — so much more effi‐
ciently, in fact, that the Swift compiler will actually call your attention to any case of
your using var where you could have used let, offering to change it for you.
Variables also have a type. This type is established when the variable is declared and
can never change. For example, this won’t compile:
var two = 2
two = "hello" // compile error
Variables | 7
Random documents with unrelated
content Scribd suggests to you:
"Sinun täytyy säilyttää rohkeutesi, Mercy. Minä puhuin ankarasti
sinulle tässä yhtenä iltana, mutta se on ohi nyt, uskothan sen?"
"Minä tulin toissa iltana, mutta näin sinun veljesi Paulin kävelevän
täällä, ja menin pois."
"Paulin?"
"Sitten minä tulin eilen illalla, mutta hän oli täällä taas ja minun
täytyi vieläkin palata. Sentähden minä tänään tulin aikaisemmin eikä
häntä ollut täällä. Mutta juuri kun minä aioin soittaa ja sanoa, että
minä olen koditon ja että minun silmäni tulevat yhä pahemmiksi,
jokin tuntui sanovan minulle, että ne kysyvät, eikö minulla ole isää ja
minkätähden minä olen jättänyt hänet. Silloin minä en voinut soittaa
— ja silloin minä toivoin, että voisin kuolla — niin, jos voisin kuolla ja
unohtaa eikä koskaan enää aamulla herätä —"
"Ah!"
"Paul tulee varmaan tänäkin iltana. Minä tahdon, että sinä odotat
ja puhuttelet häntä."
"Kyllä, kyllä."
"Kyllä."
"Kello kymmenen."
"Nyt se on jo paljon yli yhdeksän. Pyydä häntä menemään heti
Hendoniin ja kun hän lähtee, tule sinä hänen kanssaan.
Ymmärrätkö?"
"Kyllä."
"Ja nyt hyvää yötä tunniksi tai pariksi, sinä pikku lemmikki."
Hugh Ritson astui kiireesti Dean Yardin läpi Sanctuarya kohden. Kun
hän kääntyi Parlamentin kadulle, puolikuu kohosi Westminster Hallin
yli. Mutta yö oli vieläkin pimeä.
*****
"Sivumennen, rouva Drayton", hän sanoi, "te voi sitte antaa tytön
joskus auttaa itseänne."
"Ajatelkaahan. Eikö ole mitään, mitä tyttö voisi tehdä, kun hän
tulee — ei mitään palvelusta, ei askareita?"
"Aivan oikein, rouva Drayton. Lähettäkää tyttö sinne heti, kun hän
tulee ja pitäkää siellä maatamenoon asti."
"Eikö ole kylmä ilman takkia, vai?" sanoi Hugh. Hänen huulensa
vääntyivät irviin.
"Minä en välitä siitä, mikä hänen oikea nimensä on, enempää kuin
siitäkään, mikä on väärä. Se ei merkitse minulle mitään, sanon minä,
ja sillä hyvä."
"Mitä?"
"Sääli on, että te voitte täällä joutua kiinni sen sijaan, että olisitte
vapaana ja turvassa", sanoi Hugh.
"Minun vaimoni?"
"Mitä?"
"Mitäs sinä kikatat, häh?" sanoi Gubblum. "Minä sanon, että ilma
on kuuma, jos tahron. Sinä et siitä mitään tierä, vai?"
"Voinko minä saara täällä yösijan?" hän kysyi, kun Jabez oli tuonut
hänelle oluen.
"Minä tunsin kerran miehen, joka väitti, että sinun isäntäsi oli
jymäyttänyt muuatta pitkätukkaista", sanoi Gubblum. "Minä ajattelin,
että hän itse oli jymäyttänyt. Mutta kun minä sanoin sen hänelle,
hän tarttui minua niskasta kiinni ja nutisti katuun, ja kaikki vain siksi,
että minä puolustin sinun isäntääsi."
"Mitä ei ole?"
"Herraa."
*****
"Ei, ei, ei — antakaa minun kävellä. Minä voin, hyvin, minä voin
hyvin."
Näin sanoen hän kääntyi taloon, mutta tuskin oli ottanut pari
askelta kun horjahti taaskin ja vaipui portaille.
"Eikä mitään keinoa viillyttää sitä", sanoi ajuri. "Asuuko hän täällä,
rouva?"
Rouva Drayton toi lasin vettä. Paul tyhjensi sen viime tippaan.
Paul Ritsonin pää oli painunut rinnalle. Hänen hattunsa oli poissa
ja hiukset valuivat silmille: Vahva mies istui kokoonlyyhistyneenä
penkillä. Hän koetti kohentaa itseänsä ja pudistaa päältään tämän
kauhean voimattomuuden, joka oli hänet vallannut.
"Oh, oh, kuka olisi luullut? Vettä — lisää vettä", hän pyysi heikolla
äänellä.
Kun mies pääsi ovesta ulos, Hugh Ritson kääntyi rouva Draytoniin.
Kapakan emäntä löntysti ympäri huonetta hypistellen hermostuneesti
esiliinaansa. "Rouva Drayton", sanoi Hugh, "teidän on mentävä
ajurin kanssa pyhän Margaretin Westminsterin luostariin. Siellä
teidän on kysyttävä rouva Ritsonia, sitä rouvaa, joka jätti nuo tavarat
tänne perjantai-iltana. Teidän tulee sanoa hänelle, että teillä on
hänen tavaransa mukananne ja että hänen tulee seurata teitä St.
Pancraksen asemalle, jossa hän kohtaa miehensä ja sieltä he
matkustavat takaisin Cumberlandiin yöjunalla. Ymmärrättekö?"
"Oh! Sen minä voin kyllä sanoa nähtyäni, että se herraparka oli
aivan tajuton."
"Vait!"
Ajuri tuli ulos. Hän hyppäsi istuimelleen. Seuraavana hetkenä
vaunut jyrisivät tiehensä.
Hugh Ritson palasi sisään. Jabez oli tullut alas. "Mihin aikaan te
suljette kapakan?" kysyi Hugh.
"Täällä ei ole ketään. Te melkein yhtä hyvin voisitte sulkea sen nyt
heti paikalla. Ei väliä. Mene nukkumaan, poikaseni. Mercy, sinun
silmäsi ovat punaisemmat kuin koskaan ennen. Mene sinäkin
vuoteeseen arvelematta."
"Mercy!"
"Ja minä olen johtanut sinut tänne valheella", hän ajatteli. Hänen
päätänsä pyörrytti ja hän nojasi sitä vuoteen päähän. Muutamia
minuutteja kului äänettömyydessä. Hän kuuli askeleita ulkopuolelta.
Ne lähenivät tätä huonetta. Selällään oleva ovi liikahti. Kun Mercyllä
ei ollut aikaa paeta, hän painautui pimeässä piiloon sängyn ja seinän
väliin.
"Hän on kyllin vaaraton vielä", sanoi ääni, joka viilteli Mercyn koko
olentoa kuin tulinen miekka. "Nyt asiaan, ei ole hetkeäkään hukata."
Mercy kuuli toisen mutistun kirouksen. Taivaan herra! Mitä nyt oli
tekeillä? Voisiko hän paeta? Ovi oli lukossa. Jos hän voisi päästä
sinne, hän voisi avata sen ja paeta.
"Hyst!"
"Ja niin sopivat — ihan kuin tehdyt — saatana!" hän sanoi lausuen
d:n ihan oikein, vaikka se tavallisesti oli r.
Hugh Ritson astui Draytonin rinnalle. Kun hän puhui, oli hänen
äänensä kylmä kuin jäätävä viima.
"Kuule nyt. Tästä hetkestä, jolloin sinä muutat pukua, sinä lakkaat
olemasta Paul Drayton ja muutut Paul Ritsoniksi."
"Valmis."
*****
"Ei sun tartte pelätä mua. En mää aio sull' pahaa tehrä", sanoi
Gubblum leveimmällä murteellansa. Jabez työnsi oven auki. "Hänen
päänsä on pudingista ja pannurieskasta", ajatteli Gubblum.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com