SlideShare a Scribd company logo
Ios 12 Programming Fundamentals With Swift Swift
Xcode And Cocoa Basics 5th Edition Matt Neuburg
download
https://ebookbell.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-
neuburg-22034678
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa
Basics Matt Neuburg
https://ebookbell.com/product/ios-12-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-matt-neuburg-153701528
Ios 12 Programming Fundamentals With Swift Matt Neuburg
https://ebookbell.com/product/ios-12-programming-fundamentals-with-
swift-matt-neuburg-170540748
Ios 12 Programming For Beginners An Introductory Guide To Ios App
Development With Swift 42 And Xcode 10 Third Edition Clayton
https://ebookbell.com/product/ios-12-programming-for-beginners-an-
introductory-guide-to-ios-app-development-with-swift-42-and-
xcode-10-third-edition-clayton-11793154
Mastering Ios 12 Programming Third Edition Donny Wals
https://ebookbell.com/product/mastering-ios-12-programming-third-
edition-donny-wals-61024906
Programming Ios 12 Dive Deep Into Views View Controllers And
Frameworks Matt Neuburg
https://ebookbell.com/product/programming-ios-12-dive-deep-into-views-
view-controllers-and-frameworks-matt-neuburg-22124124
Programming Ios 12 Matt Neuburg
https://ebookbell.com/product/programming-ios-12-matt-
neuburg-170810434
Ios Programming For Beginners Learn Ios 15 Swift 53 And Swiftui And
Xcode 123 Step By Step Very Easy Rizk
https://ebookbell.com/product/ios-programming-for-beginners-learn-
ios-15-swift-53-and-swiftui-and-xcode-123-step-by-step-very-easy-
rizk-37232402
Ios Programming For Beginners Learn Ios 15 Swift 53 And Swiftui And
Xcode 123 Step By Step Very Easy 1st Edition Rizk
https://ebookbell.com/product/ios-programming-for-beginners-learn-
ios-15-swift-53-and-swiftui-and-xcode-123-step-by-step-very-easy-1st-
edition-rizk-50580692
Ios 14 Programming For Beginners Fifth Edition Get Started With
Building Ios Apps With Swift 53 And Xcode 12 5th Edition Ahmad Sahar
https://ebookbell.com/product/ios-14-programming-for-beginners-fifth-
edition-get-started-with-building-ios-apps-with-swift-53-and-
xcode-12-5th-edition-ahmad-sahar-217628142
Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th Edition Matt Neuburg
Matt Neuburg
iOS 12
Programming
Fundamentals
with Swift
SWIFT, XCODE, AND COCOA BASICS
C
o
v
e
r
s
i
O
S
1
2
,
X
c
o
d
e
1
0
,
a
n
d
S
w
i
f
t
4
.
2
Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th Edition Matt Neuburg
Matt Neuburg
Boston
iOS 12 Programming
Fundamentals with Swift
Swift, Xcode, and Cocoa Basics
FIFTH EDITION
ISBN: 978-1-492-04455-0
[LSI]
iOS 12 Programming Fundamentals with Swift, Fifth Edition
by Matt Neuburg
Copyright © 2018 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://oreilly.com/safari). For more information, contact our corporate/insti‐
tutional sales department: 800-998-9938 or corporate@oreilly.com.
Editor: Rachel Roumeliotis
Production Editor: Kristen Brown
Proofreader: O’Reilly Production Services
Indexer: Matt Neuburg
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Matt Neuburg
April 2015: First Edition
October 2015: Second Edition
October 2016: Third Edition
October 2017: Fourth Edition
September 2018: Fifth Edition
Revision History for the Fifth Edition
2018-09-26: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781492044550 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 12 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.
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
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 13
Namespaces 13
Modules 14
Instances 15
Why Instances? 17
The Keyword self 19
Privacy 20
Design 22
Object Types and APIs 23
Instance Creation, Scope, and Lifetime 25
Summary and Conclusion 25
2. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Function Parameters and Return Value 27
Void Return Type and Parameters 31
Function Signature 32
External Parameter Names 32
iii
Overloading 34
Default Parameter Values 35
Variadic Parameters 35
Ignored Parameters 36
Modifiable Parameters 37
Function in Function 40
Recursion 42
Function As Value 42
Anonymous Functions 45
Define-and-Call 51
Closures 52
How Closures Improve Code 54
Function Returning Function 55
Closure Setting a Captured Variable 58
Closure Preserving Its Captured Environment 59
Escaping Closures 60
Curried Functions 60
Function References and Selectors 62
Function Reference Scope 64
Selectors 65
3. Variables and Simple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Variable Scope and Lifetime 69
Variable Declaration 71
Computed Initializer 74
Computed Variables 76
Setter Observers 79
Lazy Initialization 80
Built-In Simple Types 82
Bool 82
Numbers 84
String 92
Character and String Index 96
Range 101
Tuple 103
Optional 105
4. Object Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Object Type Declarations and Features 119
Initializers 121
Properties 127
Methods 130
iv | Table of Contents
Subscripts 132
Nested Object Types 135
Instance References 135
Enums 137
Raw Values 138
Associated Values 140
Enum Case Iteration 142
Enum Initializers 143
Enum Properties 144
Enum Methods 145
Why Enums? 146
Structs 147
Struct Initializers, Properties, and Methods 147
Struct As Namespace 149
Classes 149
Value Types and Reference Types 150
Subclass and Superclass 156
Class Initializers 161
Class Deinitializer 169
Class Properties and Methods 170
Polymorphism 172
Casting 175
Casting Down 176
Type Testing and Casting Down Safely 176
Type Testing and Casting Optionals 178
Bridging to Objective-C 178
Type References 180
From Instance to Type 180
Type as Value 181
The Keyword Self 183
Comparing Types 184
Summary of Type Terminology 185
Protocols 186
Why Protocols? 187
Protocol Type Testing and Casting 189
Declaring a Protocol 190
Protocol Composition 191
Optional Protocol Members 192
Class Protocol 194
Implicitly Required Initializers 195
Literal Convertibles 196
Generics 197
Table of Contents | v
Generic Declarations 200
Contradictory Resolution 202
Type Constraints 203
Explicit Specialization 205
Generic Invariance 207
Associated Type Chains 208
Where Clauses 210
Extensions 213
Extending Object Types 213
Extending Protocols 215
Extending Generics 217
Umbrella Types 219
Any 219
AnyObject 221
AnyClass 223
Collection Types 224
Array 224
Dictionary 240
Set 247
5. Flow Control and More. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Flow Control 253
Branching 254
Loops 266
Jumping 271
Privacy 286
Private and Fileprivate 288
Public and Open 289
Privacy Rules 290
Introspection 290
Operators 291
Synthesized Protocol Implementations 295
Key Paths 298
Dynamic Member Lookup 300
Memory Management 301
Memory Management of Reference Types 301
Exclusive Access to Value Types 308
Part II. IDE
vi | Table of Contents
6. Anatomy of an Xcode Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
New Project 313
The Project Window 315
The Navigator Pane 317
The Utilities Pane 322
The Editor 323
The Project File and Its Dependents 325
What’s In the Project Folder 326
Groups 327
The Target 328
Build Phases 328
Build Settings 330
Configurations 331
Schemes and Destinations 333
From Project to Built App 335
Build Settings 338
Property List Settings 338
Nib Files 339
Additional Resources 340
Code Files 342
Frameworks and SDKs 343
The App Launch Process 345
The Entry Point 345
UIApplicationMain 346
App Without a Storyboard 348
Renaming Parts of a Project 349
7. Nib Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
The Nib Editor Interface 352
Document Outline 353
Canvas 356
Inspectors and Libraries 358
Nib Loading 359
When Nibs Are Loaded 360
Manual Nib Loading 361
Connections 363
Outlets 363
The Nib Owner 364
Automatically Configured Nibs 368
Misconfigured Outlets 369
Deleting an Outlet 371
More Ways to Create Outlets 372
Table of Contents | vii
Outlet Collections 374
Action Connections 375
More Ways to Create Actions 377
Misconfigured Actions 379
Connections Between Nibs — Not! 379
Additional Configuration of Nib-Based Instances 380
8. Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
The Documentation Window 385
Class Documentation Pages 386
Quick Help 390
Symbol Declarations 392
Header Files 393
Sample Code 394
Internet Resources 394
9. Life Cycle of a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
Environmental Dependencies 397
Permissible Runtime Environment 398
Backward Compatibility 398
Device Type 400
Arguments and Environment Variables 401
Conditional Compilation 402
Version Control 404
Editing and Navigating Your Code 407
Autocompletion 409
Snippets 410
Fix-it and Live Syntax Checking 412
Navigation 413
Finding 415
Refactoring 416
Running in the Simulator 416
Debugging 417
Caveman Debugging 417
The Xcode Debugger 420
Testing 427
Unit Tests 428
Interface Tests 431
Clean 433
Running on a Device 433
Obtaining a Developer Program Membership 434
Signing an App 435
viii | Table of Contents
Automatic Signing 436
Manual Signing 439
Running the App 441
Managing Development Certificates and Devices 442
Profiling 442
Gauges 442
Memory Debugging 444
Instruments 445
Localization 448
Distribution 453
Making an Archive 453
The Distribution Certificate 454
The Distribution Profile 456
Distribution for Testing 457
Final App Preparations 458
Screenshots and Video Previews 461
Property List Settings 463
Submission to the App Store 464
Part III. Cocoa
10. Cocoa Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Subclassing 469
Categories and Extensions 472
How Swift Uses Extensions 472
How You Use Extensions 473
How Cocoa Uses Categories 473
Protocols 475
Informal Protocols 477
Optional Methods 477
Some Foundation Classes 480
NSRange and NSNotFound 481
NSString and Friends 483
NSDate and Friends 486
NSNumber 487
NSValue 489
NSData 490
NSMeasurement and Friends 491
Equality, Hashability, and Comparison 491
NSArray and NSMutableArray 494
NSDictionary and NSMutableDictionary 496
Table of Contents | ix
NSSet and Friends 496
NSIndexSet 497
NSNull 498
Immutable and Mutable 498
Property Lists 500
Codable 501
Accessors, Properties, and Key–Value Coding 504
Swift Accessors 505
Key–Value Coding 507
Uses of Key–Value Coding 508
KVC and Outlets 510
Cocoa Key Paths 510
The Secret Life of NSObject 511
11. Cocoa Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
Reasons for Events 513
Subclassing 514
Notifications 516
Receiving a Notification 517
Unregistering 519
Posting a Notification 520
Timer 521
Delegation 523
Cocoa Delegation 523
Implementing Delegation 525
Data Sources 527
Actions 527
The Responder Chain 530
Deferring Responsibility 531
Nil-Targeted Actions 532
Key–Value Observing 533
Registration and Notification 534
Unregistering 535
Key–Value Observing Example 536
Swamped by Events 537
Delayed Performance 540
12. Memory Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
Principles of Cocoa Memory Management 543
Rules of Cocoa Memory Management 544
What ARC Is and What It Does 545
How Cocoa Objects Manage Memory 546
x | Table of Contents
Autorelease Pool 547
Memory Management of Instance Properties 549
Retain Cycles and Weak References 550
Unusual Memory Management Situations 552
Notification Observers 552
KVO Observers 554
Timers 554
Other Unusual Situations 556
Nib Loading and Memory Management 556
Memory Management of CFTypeRefs 557
Property Memory Management Policies 559
Debugging Memory Management Mistakes 561
13. Communication Between Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
Visibility by Instantiation 564
Visibility by Relationship 566
Global Visibility 567
Notifications and Key–Value Observing 569
Model–View–Controller 569
A. C, Objective-C, and Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
Table of Contents | xi
Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th Edition Matt Neuburg
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 consider
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 Swift deserved to be, and probably would be, adopted by
new students of iOS programming, and that my books, therefore, should henceforth
assume that readers are using Swift.
That decision has proven prophetic. Programmers of iOS have flocked to Swift in
increasing numbers, and Swift itself has only improved. My iOS apps (such as Diabel‐
li’s Theme, LinkSame, Zotz!, TidBITS News, and my Latin and Greek flashcard apps)
have all been rewritten in Swift, and are far easier for me to understand and maintain
than their Objective-C originals.
Xcode 10 comes with Swift 4.2. The language has evolved greatly in its details and in
the nature of its integration with the Cocoa libraries that underlie iOS programming,
but its spirit has remained constant. 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.
xiii
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.
Memory management
Swift manages memory automatically. You will rarely have to concern yourself
with memory management.
Cocoa compatibility
The Cocoa APIs are written primarily 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.
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.
Still, the reader may 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 might have to know what those lan‐
guages would expect.
xiv | Preface
Therefore, although I do not attempt to teach Objective-C in this book, I do describe
it in enough detail to allow you to read it when you encounter it in the documenta‐
tion and on the Internet, and I occasionally show some Objective-C code. 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 commu‐
nicate with one another, as well as explaining how your app can be written partly in
Swift and partly in Objective-C.
The Scope of This Book
This book is actually one of a pair with my Programming iOS 12, which picks up
exactly where this book leaves off. They complement and supplement one another.
The two-book architecture should, I believe, render the size and scope of each book
tractable for readers. Together, they provide a complete grounding in the knowledge
needed to begin writing iOS apps; thus, when you do start writing iOS apps, you’ll
have a solid and rigorous understanding of what you are doing and where you are
heading. If writing an iOS program is like building a house of bricks, this book
teaches you what a brick is and how to handle it, while Programming iOS 12 hands
you some actual bricks and tells you how to assemble them.
When you have read this book, you’ll know about Swift, Xcode, and the underpin‐
nings of the Cocoa framework, and you will be ready to proceed directly to Program‐
ming iOS 12. Conversely, Programming iOS 12 assumes a knowledge of this book; it
begins, like Homer’s Iliad, in the middle of the story, with the reader jumping with all
four feet into views and view controllers, and with a knowledge of the language and
the Xcode IDE already presupposed. If you started reading Programming iOS 12 and
wondered about such unexplained matters as Swift language basics, the
UIApplicationMain function, the nib-loading mechanism, Cocoa patterns of delega‐
tion and notification, and retain cycles, wonder no longer — I didn’t explain them
there because I do explain them here.
The three parts of this book teach the underlying basis of all iOS programming:
• 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
Preface | xv
Swift playgrounds or the REPL. My focus here is real-life iOS programming, and
my explanation of Swift therefore concentrates on those common, practical
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 12, of course!
Versions
This book is geared to Swift 4.2, iOS 12, and Xcode 10.
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).
xvi | Preface
A word about method names. I generally give method names in Swift, in the style of a
function reference (as described in Chapter 2) — that is, the name plus parentheses
containing the parameter labels followed by colon. 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 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 10 under macOS 10.13 High Sierra. I
have not upgraded my machine to macOS 10.14 Mojave, 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 running Mojave, your interface may naturally look slightly different from
the screenshots (especially if you’re using “dark mode”), but this difference will be
minimal and shouldn’t cause any confusion.
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.
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)
Preface | xvii
• 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.
From the Programming iOS 4 Preface
A programming framework has a kind of personality, an overall flavor that provides
an insight into the goals and mindset of those who created it. When I first encoun‐
tered Cocoa Touch, my assessment of its personality was: “Wow, the people who
wrote this are really clever!” On the one hand, the number of built-in interface
objects was severely and deliberately limited; on the other hand, the power and flexi‐
bility of some of those objects, especially such things as UITableView, was greatly
enhanced over their OS X counterparts. Even more important, Apple created a partic‐
ularly brilliant way (UIViewController) to help the programmer make entire blocks
of interface come and go and supplant one another in a controlled, hierarchical man‐
ner, thus allowing that tiny iPhone display to unfold virtually into multiple interface
worlds within a single app without the user becoming lost or confused.
The popularity of the iPhone, with its largely free or very inexpensive apps, and the
subsequent popularity of the iPad, have brought and will continue to bring into the
fold many new programmers who see programming for these devices as worthwhile
and doable, even though they may not have felt the same way about OS X. Apple’s
own annual WWDC developer conventions have reflected this trend, with their
emphasis shifted from OS X to iOS instruction.
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.
xviii | Preface
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.
Conventions Used in This Book
The following typographical conventions are used in this book:
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.
This element signifies a tip or suggestion.
Preface | xix
This element signifies a general note.
This element indicates a warning or caution.
Using Code Examples
Supplemental material (code examples, exercises, etc.) is available for download at
http://github.com/mattneub/Programming-iOS-Book-Examples.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not
need to contact us for permission unless you’re reproducing a significant portion of
the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing a CD-ROM of examples
from O’Reilly books does require permission. Answering a question by citing this
book and quoting example code does not require permission. Incorporating a signifi‐
cant amount of example code from this book into your product’s documentation does
require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “iOS 12 Programming Fundamentals
with Swift by Matt Neuburg (O’Reilly). Copyright 2018 Matt Neuburg,
978-1-492-04455-0.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari (formerly Safari Books Online) is a membership-
based training and reference platform for enterprise, gov‐
ernment, educators, and individuals.
Members have access to thousands of books, training videos, Learning Paths, interac‐
tive tutorials, and curated playlists from over 250 publishers, including O’Reilly
Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐
sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press,
John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe
Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and
Course Technology, among others.
xx | Preface
For more information, please visit http://oreilly.com/safari.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
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/ios12-prog-fundamentals.
To comment or ask technical questions about this book, send email to bookques‐
tions@oreilly.com.
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
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Preface | xxi
Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th Edition Matt Neuburg
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
programming.
• 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 describe Swift access
control (privacy), introspection (reflection), and how to create your own opera‐
tors. There follows a discussion of some recently added Swift language features:
synthesized protocol implementations, key paths, and dynamic member lookup.
The chapter concludes by considering Swift 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")
(The print command provides instant feedback in the Xcode console.)
You can combine more than one statement on a line, but then you need to put a
semicolon between them:
print("hello"); print("world")
You are free to put a semicolon at the end of a statement that is last or alone on its
line, but no one ever does (except out of habit, because C and Objective-C require the
semicolon):
print("hello");
print("world");
Conversely, a single statement can be broken into multiple lines, in order to prevent
long statements from becoming long lines. But you should try to do this at sensible
places so as not to confuse Swift. For example, after an opening parenthesis is a good
place:
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 runs.
The Swift compiler’s error and warning messages, however, 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 occa‐
sional unhelpful nature of its messages. Remember, it knows more than you do, even
if it is sometimes rather inarticulate about its knowledge.
4 | Chapter 1: The Architecture of Swift
Everything Is an Object?
In Swift, “everything is an object.” That’s a boast common to various modern object-
oriented languages, but what does it mean? Well, that depends on what you mean by
“object” — and what you mean by “everything.”
Let’s start by stipulating that an object, roughly speaking, is something you can send a
message to. A message, roughly speaking, is an imperative instruction. For example,
you can give commands to a dog: “Bark!” “Sit!” In this analogy, those phrases are
messages, and the dog is the object to which you are sending those messages.
In Swift, the syntax of message-sending is dot-notation. We start with the object; then
there’s a dot (a period); then there’s the message. (Some messages are also followed by
parentheses, but ignore them for now; the full syntax of message-sending is one of
those details we’ll be filling in later.) This is valid Swift syntax:
fido.bark()
rover.sit()
The idea of everything being an object is a way of suggesting that even “primitive” lin‐
guistic entities can be sent messages. Take, for example, 1. It appears to be a literal
digit and no more. It will not surprise you, if you’ve ever used any programming lan‐
guage, that you can say things like this in Swift:
let sum = 1 + 2
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.
Three Flavors of Object Type
If you know Objective-C or some other object-oriented language, you may be sur‐
prised by Swift’s notion of what kind of object 1 is. In many languages, such as
Objective-C, an object is a class or an instance of a class (I’ll explain later what an
instance is). Swift has classes, but 1 in Swift is not a class or an instance of a class: the
type of 1, namely Int, is a struct, and 1 is an instance of a struct. And Swift has yet
another kind of thing you can send messages to, called an enum.
So Swift has three kinds of object type: classes, structs, and enums. I like to refer to
these as the three flavors of object type. Exactly how they differ from one another will
emerge in due course. But they are all very definitely object types, and their similari‐
ties to one another are far stronger than their differences. For now, just bear in mind
that these three flavors exist.
(The fact that a struct or enum is an object type in Swift will surprise you particularly
if you know Objective-C. Objective-C has structs and enums, but they are not objects.
Swift structs, in particular, are much more important and pervasive than Objective-C
structs. This difference between how Swift views structs and enums and how
Objective-C views them can matter when you are talking to Cocoa.)
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
6 | Chapter 1: The Architecture of Swift
Once the name exists, you are free to use it. For example, we can change the value of
two to be the same as the value of one:
let one = 1
var two = 2
two = one
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
Once two is declared and initialized as 2, it is a number (properly speaking, an Int)
and it must always be so. You can replace its value with 1 because that’s also an Int,
but you can’t replace its value with "hello" because that’s a string (properly speaking,
a String) — and a String is not an Int.
Variables literally have a life of their own — more accurately, a lifetime of their own.
As long as a variable exists, it keeps its value alive. Thus, a variable can be not only a
way of conveniently naming something, but also a way of preserving it. I’ll have more
to say about that later.
Variables | 7
By convention, type names such as String or Int (or Dog or Cat) start with a capi‐
tal letter; variable names start with a small letter. Do not violate this convention. If
you do, your code might still compile and run just fine, but I will personally send
agents to your house to remove your kneecaps in the dead of night.
Functions
Executable code, like fido.bark() or one = two, cannot go just anywhere in your
program. (Failure to appreciate this fact is a common beginner mistake, and can
result in a mysterious compile error message such as “Expected declaration.”) In gen‐
eral, executable code must live inside the body of a function. A function is a batch of
code that can be told, as a batch, to run. Typically, a function has a name, and it gets
that name through a function declaration. Function declaration syntax is another of
those details that will be filled in later, but here’s an example:
func go() {
let one = 1
var two = 2
two = one
}
That describes a sequence of things to do — declare one, declare two, change the
value of two to match the value of one — and it gives that sequence a name, go; but it
doesn’t perform the sequence. The sequence is performed when someone calls the
function. Thus, we might say, elsewhere:
go()
That is a command to the go function that it should actually run. But again, that com‐
mand is itself executable code, so it cannot live on its own either. It might live in the
body of a different function:
func doGo() {
go()
}
But wait! This is getting a little nutty. That, too, is just a function declaration; to run
it, someone must call doGo by saying doGo() — and that’s executable code too. This
seems like some kind of infinite regression; it looks like none of our code will ever
run. If all executable code has to live in a function, who will tell any function to run?
The initial impetus must come from somewhere.
In real life, fortunately, this regression problem doesn’t arise. Remember that your
goal is ultimately to write an iOS app. Thus, your app will be run on an iOS device (or
the Simulator) by a runtime that already wants to call certain functions. So you start
by writing special functions that you know the runtime itself will call. That gives your
app a way to get started and gives you places to put functions that will be called by the
8 | Chapter 1: The Architecture of Swift
runtime at key moments — such as when the app launches, or when the user taps a
button in your app’s interface.
Swift also has a special rule that a file called main.swift, exceptionally, can have
executable code at its top level, outside any function body, and this is the code
that actually runs when the program runs. You can construct your app with a
main.swift file, but in general you won’t need to.
The Structure of a Swift File
A Swift program can consist of one file or many files. In Swift, a file is a meaningful
unit, and there are definite rules about the structure of the Swift code that can go
inside it. (I’m assuming that we are not in a main.swift file.) Only certain things can
go at the top level of a Swift file — chiefly the following:
Module import statements
A module is an even higher-level unit than a file. A module can consist of multi‐
ple files, and these can all see each other automatically; but a module can’t see
another module without an import statement. For example, that is how you are
able to talk to Cocoa in an iOS program: the first line of your file says import
UIKit.
Variable declarations
A variable declared at the top level of a file is a global variable: all code will be
able to see and access it, without explicitly sending a message to any object, and it
lives as long as the program runs.
Function declarations
A function declared at the top level of a file is a global function: all code will be
able to see and call it, without explicitly sending a message to any object.
Object type declarations
The declaration for a class, a struct, or an enum.
For example, this is a legal Swift file containing (just to demonstrate that it can be
done) an import statement, a variable declaration, a function declaration, a class dec‐
laration, a struct declaration, and an enum declaration:
import UIKit
var one = 1
func changeOne() {
}
class Manny {
}
The Structure of a Swift File | 9
struct Moe {
}
enum Jack {
}
That’s a very silly and mostly empty example, but remember, our goal is to survey the
parts of the language and the structure of a file, and the example shows them.
Furthermore, the curly braces for each of the things in that example can all have vari‐
able declarations, function declarations, and object type declarations within them!
Indeed, any structural curly braces can contain such declarations.
You’ll notice that I did not say that executable code can go at the top level of a file.
That’s because it can’t! Only a function body can contain executable code. A statement
like one = two or print(name) is executable code, and can’t go at the top level of a
file. But in our previous example, func changeOne() is a function declaration, so exe‐
cutable code can go inside its curly braces, because they constitute a function body:
var one = 1
// executable code can't go here
func changeOne() {
let two = 2 // executable code
one = two // executable code
}
Executable code also can’t go directly inside the curly braces that accompany the
class Manny declaration; that’s the top level of a class declaration, not a function
body. But a class declaration can contain a function declaration, and that function
declaration can contain executable code:
class Manny {
let name = "manny"
// executable code can't go here
func sayName() {
print(name) // executable code
}
}
To sum up, Example 1-1 is a legal Swift file, schematically illustrating the structural
possibilities. (Ignore the hanky-panky with the name variable declaration inside the
enum declaration for Jack; enum top-level variables have some special rules that I’ll
explain later.)
Example 1-1. Schematic structure of a legal Swift file
import UIKit
var one = 1
func changeOne() {
let two = 2
func sayTwo() {
10 | Chapter 1: The Architecture of Swift
print(two)
}
class Klass {}
struct Struct {}
enum Enum {}
one = two
}
class Manny {
let name = "manny"
func sayName() {
print(name)
}
class Klass {}
struct Struct {}
enum Enum {}
}
struct Moe {
let name = "moe"
func sayName() {
print(name)
}
class Klass {}
struct Struct {}
enum Enum {}
}
enum Jack {
var name : String {
return "jack"
}
func sayName() {
print(name)
}
class Klass {}
struct Struct {}
enum Enum {}
}
Obviously, we can recurse down as far we like: we could have a class declaration con‐
taining a class declaration containing a class declaration, and so on. But there’s no
point illustrating that.
Scope and Lifetime
In a Swift program, things have a scope. This refers to their ability to be seen by other
things. Things are nested inside of other things, making a nested hierarchy of things.
The rule is that things can see things at their own level and at a higher level containing
them. The levels are:
• A module is a scope.
• A file is a scope.
Scope and Lifetime | 11
• Curly braces are a scope.
When something is declared, it is declared at some level within that hierarchy. Its
place in the hierarchy — its scope — determines whether it can be seen by other
things.
Look again at Example 1-1. Inside the declaration of Manny is a name variable decla‐
ration and a sayName function declaration; the code inside sayName’s curly braces can
see things outside those curly braces at a higher containing level, and can therefore see
the name variable. Similarly, the code inside the body of the changeOne function can
see the one variable declared at the top level of the file; indeed, everything throughout
this file can see the one variable declared at the top level of the file.
Scope is thus a very important way of sharing information. Two different functions
declared inside Manny would both be able to see the name declared at Manny’s top
level. Code inside Jack and code inside Moe can both see the one declared at the file’s
top level.
Things also have a lifetime, which is effectively equivalent to their scope. A thing lives
as long as its surrounding scope lives. Thus, in Example 1-1, the variable one lives as
long as the file lives — namely, as long the program runs. It is global and persistent.
But the variable name declared at the top level of Manny exists only so long as a
Manny instance exists (I’ll talk in a moment about what that means).
Things declared at a deeper level live even shorter lifetimes. Consider this code:
func silly() {
if true {
class Cat {}
var one = 1
one = one + 1
}
}
That code is silly, but it’s legal: remember, I said that variable declarations, function
declarations, and object type declarations can appear in any structural curly braces. In
that code, the class Cat and the variable one will not even come into existence until
someone calls the silly function, and even then they will exist only during the brief
instant that the path of code execution passes through the if construct. So, suppose
the function silly is called; the path of execution then enters the if construct. Here,
Cat is declared and comes into existence; then one is declared and comes into exis‐
tence; then the executable line one = one + 1 is executed; and then the scope ends
and both Cat and one vanish in a puff of smoke. And throughout their brief lives, Cat
and one were completely invisible to the rest of the program. (Do you see why?)
12 | Chapter 1: The Architecture of Swift
Object Members
Inside the three object types (class, struct, and enum), things declared at the top level
have special names, mostly for historical reasons. Let’s use the Manny class as an
example:
class Manny {
let name = "manny"
func sayName() {
print(name)
}
}
In that code:
• name is a variable declared at the top level of an object declaration, so it is called a
property of that object.
• sayName is a function declared at the top level of an object declaration, so it is
called a method of that object.
Things declared at the top level of an object declaration — properties, methods, and
any objects declared at that level — are collectively the members of that object. Mem‐
bers have a special significance, because they define the messages you are allowed to
send to that object!
Namespaces
A namespace is a named region of a program. The names of things inside a name‐
space cannot be reached by things outside it without somehow first passing through
the barrier of saying that region’s name. This is a good thing because it allows the
same name to be used in different places without a conflict. Clearly, namespaces and
scopes are closely related notions.
Namespaces help to explain the significance of declaring an object at the top level of
an object, like this:
class Manny {
class Klass {}
}
This way of declaring Klass makes Klass a nested type. It effectively “hides” Klass
inside Manny. Manny is a namespace! Code inside Manny can see (and say) Klass
directly. But code outside Manny can’t do that. It has to specify the namespace explic‐
itly in order to pass through the barrier that the namespace represents. To do so, it
must say Manny’s name first, followed by a dot, followed by the term Klass. In short,
it has to say Manny.Klass.
Object Members | 13
The namespace does not, of itself, provide secrecy or privacy; it’s a convenience.
Thus, in Example 1-1, I gave Manny a Klass class, and I also gave Moe a Klass class.
But they don’t conflict, because they are in different namespaces, and I can differenti‐
ate them, if necessary, as Manny.Klass and Moe.Klass.
It will not have escaped your attention that the syntax for diving explicitly into a
namespace is the message-sending dot-notation syntax. They are, in fact, the same
thing.
In effect, message-sending allows you to see into scopes you can’t see into otherwise.
Code inside Moe can’t automatically see the Klass declared inside Manny, but it can
see it by taking one easy extra step, namely by speaking of Manny.Klass. It can do that
because it can see Manny (because Manny is declared at a level that code inside Moe
can see).
Modules
The top-level namespaces are modules. By default, your app is a module and hence a
namespace; that namespace’s name is, roughly speaking, the name of the app. For
example, if my app is called MyApp, then if I declare a class Manny at the top level of a
file, that class’s real name is MyApp.Manny. But I don’t usually need to use that real
name, because my code is already inside the same namespace, and can see the name
Manny directly.
Frameworks are also modules, and hence they are also namespaces. When you
import a module, all the top-level declarations of that module become visible to your
code, without your having to use the module’s namespace explicitly to refer to them.
For example, Cocoa’s Foundation framework, where NSString lives, is a module.
When you program iOS, you will say import Foundation (or, more likely, you’ll say
import UIKit, which itself imports Foundation), thus allowing you to speak of
NSString without saying Foundation.NSString. But you could say
Foundation.NSString, and if you were so silly as to declare a different NSString in
your own module, you would have to say Foundation.NSString, in order to differen‐
tiate them. You can also create your own frameworks, and these, too, will be modules.
Swift itself is defined in a module — the Swift module. Your code always implicitly
imports the Swift module. You could make this explicit by starting a file with the line
import Swift; there is no need to do this, but it does no harm either.
That fact is important, because it solves a major mystery: where do things like print
come from, and why is it possible to use them outside of any message to any object?
print is in fact a function declared at the top level of the Swift module, and your code
can see the Swift module’s top-level declarations because it imports Swift. The print
function thus becomes, as far as your code is concerned, an ordinary top-level func‐
14 | Chapter 1: The Architecture of Swift
tion like any other; it is global to your code, and your code can speak of it without
specifying its namespace. You can specify its namespace — it is perfectly legal to say
things like Swift.print("hello") — but you probably never will, because there’s no
name conflict to resolve.
You can actually see the Swift top-level declarations and read and study them,
and this can be a useful thing to do. For example, to see the declaration of print,
Command-Control-click the term print in your code. Alternatively, explicitly
import Swift and Command-Control-click the term Swift. Behold, there are
the Swift top-level declarations! You won’t see any executable Swift code here, but
you will see the declarations for all the available Swift terms, including top-level
functions like print, operators like +, and built-in types such as Int and String
(look for struct Int, struct String, and so on).
Instances
Object types — class, struct, and enum — have an important feature in common: they
can be instantiated. In effect, when you declare an object type, you are only defining a
type. To instantiate a type is to make a thing — an instance — of that type.
So, for example, I can declare a Dog class, and I can give my class a method:
class Dog {
func bark() {
print("woof")
}
}
But I don’t actually have any Dog objects in my program yet. I have merely described
the type of thing a Dog would be if I had one. To get an actual Dog, I have to make
one. The process of making an actual Dog object whose type is the Dog class is the
process of instantiating Dog. The result is a new object — a Dog instance.
In Swift, instances can be created by using the object type’s name as a function name
and calling the function. This involves using parentheses. When you append paren‐
theses to the name of an object type, you are sending a very special kind of message
to that object type: Instantiate yourself!
So now I’m going to make a Dog instance:
let fido = Dog()
There’s a lot going on in that code! I did two things. I instantiated Dog, thus causing
me to end up with a Dog instance. I also put that Dog instance into a shoebox called
fido — I declared a variable and initialized the variable by assigning my new Dog
instance to it. Now fido is a Dog instance. (Moreover, because I used let, fido will
always be this same Dog instance. I could have used var instead, but even then,
Instances | 15
Figure 1-1. Making an instance and calling an instance method
initializing fido as a Dog instance would have meant fido could only be some Dog
instance after that.)
Now that I have a Dog instance, I can send instance messages to it. And what do you
suppose they are? They are Dog’s properties and methods! For example:
let fido = Dog()
fido.bark()
That code is legal. Not only that, it is effective: it actually does cause "woof" to appear
in the console. I made a Dog and I made it bark! (See Figure 1-1.)
There’s an important lesson here, so let me pause to emphasize it. By default, proper‐
ties and methods are instance properties and methods. You can’t use them as mes‐
sages to the object type itself; you have to have an instance to send those messages to.
As things stand, this is illegal and won’t compile:
Dog.bark() // compile error
It is possible to declare a function bark in such a way that saying Dog.bark() is legal,
but that would be a different kind of function — a class function or a static function
— and you would need to say so when you declare it.
The same thing is true of properties. To illustrate, let’s give Dog a name property:
class Dog {
var name = ""
}
That allows me to set a Dog’s name, but it needs to be an instance of Dog:
16 | Chapter 1: The Architecture of Swift
let fido = Dog()
fido.name = "Fido"
It is possible to declare a property name in such a way that saying Dog.name is legal,
but that would be a different kind of property — a class property or a static property
— and you would need to say so when you declare it.
Why Instances?
Even if there were no such thing as an instance, an object type is itself an object. We
know this because it is possible to send a message to an object type (the phrase
Manny.Klass is a case in point). Why, then, do instances exist at all?
The answer has mostly to do with the nature of instance properties. The value of an
instance property is defined with respect to a particular instance. This is where
instances get their real usefulness and power.
Consider again our Dog class. I’ll give it a name property and a bark method; remem‐
ber, these are an instance property and an instance method:
class Dog {
var name = ""
func bark() {
print("woof")
}
}
A Dog instance comes into existence with a blank name (an empty string). But its
name property is a var, so once we have any Dog instance, we can assign to its name a
new String value:
let dog1 = Dog()
dog1.name = "Fido"
We can also ask for a Dog instance’s name:
let dog1 = Dog()
dog1.name = "Fido"
print(dog1.name) // "Fido"
The important thing is that we can make more than one Dog instance, and that two
different Dog instances can have two different name property values (Figure 1-2):
let dog1 = Dog()
dog1.name = "Fido"
let dog2 = Dog()
dog2.name = "Rover"
print(dog1.name) // "Fido"
print(dog2.name) // "Rover"
Why Instances? | 17
Figure 1-2. Two dogs with different property values
Note that a Dog instance’s name property has nothing to do with the name of the vari‐
able to which a Dog instance is assigned. The variable is just a shoebox. You can pass
an instance from one shoebox to another. But the instance itself maintains its own
internal integrity:
let dog1 = Dog()
dog1.name = "Fido"
var dog2 = Dog()
dog2.name = "Rover"
print(dog1.name) // "Fido"
print(dog2.name) // "Rover"
dog2 = dog1
print(dog2.name) // "Fido"
That code didn’t change Rover’s name; it changed which dog was inside the dog2 shoe‐
box, replacing Rover with Fido.
The full power of object-based programming has now emerged. There is a Dog object
type which defines what it is to be a Dog. Our declaration of Dog says that a Dog
instance — any Dog instance, every Dog instance — has a name property and a bark
method. But each Dog instance can have its own name property value. They are differ‐
ent instances and maintain their own internal state. So multiple instances of the same
object type behave alike — both Fido and Rover can bark, and will do so when they
are sent the bark message — but they are different instances and can have different
property values: Fido’s name is "Fido" while Rover’s name is "Rover".
18 | Chapter 1: The Architecture of Swift
So an instance is a reflection of the instance methods of its type, but that isn’t all it is;
it’s also a collection of instance properties. The object type is responsible for what
properties the instance has, but not necessarily for the values of those properties. The
values can change as the program runs, and apply only to a particular instance. An
instance is a cluster of particular property values.
An instance is responsible not only for the values but also for the lifetimes of its prop‐
erties. Suppose we bring a Dog instance into existence and assign to its name property
the value "Fido". Then this Dog instance is keeping the string "Fido" alive just so
long as we do not replace the value of its name with some other value — and just so
long as this instance lives.
In short, an instance is both code and data. The code it gets from its type and in a
sense is shared with all other instances of that type, but the data belong to it alone.
The data can persist as long as the instance persists. The instance has, at every
moment, a state — the complete collection of its own personal property values. An
instance is a device for maintaining state. It’s a box for storage of data.
The Keyword self
An instance is an object, and an object is the recipient of messages. Thus, an instance
needs a way of sending a message to itself. This is made possible by the keyword self.
This word can be used wherever an instance of the appropriate type is expected.
For example, let’s say I want to keep the thing that a Dog says when it barks, such as
"woof", in a property. Then in my implementation of bark I need to refer to that
property. I can do it like this:
class Dog {
var name = ""
var whatADogSays = "woof"
func bark() {
print(self.whatADogSays)
}
}
Similarly, let’s say I want to write an instance method speak which is merely a syno‐
nym for bark. My speak implementation can consist of simply calling my own bark
method. I can do it like this:
class Dog {
var name = ""
var whatADogSays = "woof"
func bark() {
print(self.whatADogSays)
}
The Keyword self | 19
func speak() {
self.bark()
}
}
Observe that the term self in that example appears only in instance methods. When
an instance’s code says self, it is referring to this instance. If the expression
self.name appears in a Dog instance method’s code, it means the name of this Dog
instance, the one whose code is running at that moment.
It turns out that every use of the word self I’ve just illustrated is completely optional.
You can omit it and all the same things will happen:
class Dog {
var name = ""
var whatADogSays = "woof"
func bark() {
print(whatADogSays)
}
func speak() {
bark()
}
}
The reason is that if you omit the message recipient and the message you’re sending
can be sent to self, the compiler supplies self as the message’s recipient under the
hood. However, I never do that (except by mistake). As a matter of style, I like to be
explicit in my use of self. I find code that omits self harder to read and understand.
And there are situations where you must say self, so I prefer to use it whenever I’m
allowed to.
Privacy
Earlier, I said that a namespace is not, of itself, an insuperable barrier to accessing the
names inside it. But such a barrier is sometimes desirable. For example, not all data
stored by an instance is intended for alteration by, or even visibility to, another
instance. And not every instance method is intended to be called by other instances.
Any decent object-based programming language needs a way to endow its object
members with privacy — a way of making it harder for other objects to see those
members if they are not supposed to be seen.
Consider, for example:
class Dog {
var name = ""
var whatADogSays = "woof"
func bark() {
print(self.whatADogSays)
}
20 | Chapter 1: The Architecture of Swift
func speak() {
print(self.whatADogSays)
}
}
Here, other objects can come along and change my property whatADogSays. Since
that property is used by both bark and speak, we could easily end up with a Dog that,
when told to bark, says "meow". That seems somehow undesirable:
let dog1 = Dog()
dog1.whatADogSays = "meow"
dog1.bark() // meow
You might reply: Well, silly, why did you declare whatADogSays with var? Declare it
with let instead. Make it a constant! Now no one can change it:
class Dog {
var name = ""
let whatADogSays = "woof"
func bark() {
print(self.whatADogSays)
}
func speak() {
print(self.whatADogSays)
}
}
That is a good answer, but it is not quite good enough. There are two problems. Sup‐
pose I want a Dog instance itself to be able to change its own whatADogSays — by
assigning to self.whatADogSays. Then whatADogSays has to be a var; otherwise,
even the instance itself can’t change it. Also, suppose I don’t want any other object to
know what this Dog says, except by calling bark or speak. Even when declared with
let, other objects can still read the value of whatADogSays. Maybe I don’t like that.
To solve this problem, Swift provides the private keyword. I’ll talk later about all the
ramifications of this keyword, but for now it’s enough to know that it solves the
problem:
class Dog {
var name = ""
private var whatADogSays = "woof"
func bark() {
print(self.whatADogSays)
}
func speak() {
print(self.whatADogSays)
}
}
Now name is a public property, but whatADogSays is a private property: it can’t be seen
by other types of object. A Dog instance can speak of self.whatADogSays, but a Cat
Privacy | 21
Reserved Words
Certain terms, like class and func and var and let and if and private and import,
are reserved in Swift; they are part of the language. That means you can’t use them as
identifiers — as the name of a class, a function, or a variable, for example. If you try to
do so, you’ll get a compile error.
To force a reserved word to be an identifier, surround it by backticks (`). This (extra‐
ordinarily confusing) code is legal:
class `func` {
func `if`() {
let `class` = 1
}
}
instance with a reference to a Dog instance as fido cannot say fido.whatADogSays.
The important lesson here is that object members are public by default, and if you
want privacy, you have to ask for it.
To sum up: A class declaration defines a namespace. This namespace requires that
other objects use an extra level of dot-notation to refer to what’s inside the name‐
space, but other objects can still refer to what’s inside the namespace; the namespace
does not, in and of itself, close any doors of visibility. The private keyword lets you
close those doors.
Design
What object types will your program need, what methods and properties should they
have, when and how will they be instantiated, and what should you do with those
instances when you have them? Those aren’t easy decisions, and there are no clear-cut
answers. Object-based programming is an art.
In real life, when you’re programming iOS, many object types you’ll be working with
will not be yours but Apple’s. Swift itself comes with a few useful object types, such as
String and Int; you’ll also import UIKit, which includes a huge number of object
types, all of which spring to life in your program. You didn’t create any of those object
types, so their design is not your problem; instead, you must learn to use them.
Apple’s object types are aimed at enabling the general functionality that any app might
need. At the same time, your app will probably have specific functionality, unique to
its purpose, and you will have to design object types to serve that purpose.
Object-based program design must be founded upon a secure understanding of the
nature of objects. You want to design object types that encapsulate the right sort of
functionality (methods) accompanied by the right set of data (properties). Then,
22 | Chapter 1: The Architecture of Swift
when you instantiate those object types, you want to make sure that your instances
have the right lifetimes, sufficient exposure to one another, and an appropriate ability
to communicate with one another.
Object Types and APIs
Your program files will have very few, if any, top-level functions and variables. Meth‐
ods and properties of object types — in particular, instance methods and instance
properties — will be where most of the action is. Object types give each actual
instance its specialized abilities. They also help to organize your program’s code
meaningfully and maintainably.
We may summarize the nature of objects in two phrases: encapsulation of functional‐
ity, and maintenance of state. (I first used this summary many years ago in my book
REALbasic: The Definitive Guide.)
Encapsulation of functionality
Each object does its own job, and presents to the rest of the world — to other
objects, and indeed in a sense to the programmer — an opaque wall whose only
entrances are the methods to which it promises to respond and the actions it
promises to perform when the corresponding messages are sent to it. The details
of how, behind the scenes, it actually implements those actions are secreted
within itself; no other object needs to know them.
Maintenance of state
Each individual instance is a bundle of data that it maintains. Often that data is
private, so it’s encapsulated as well; no other object knows what that data is or in
what form it is kept. The only way to discover from outside what private data an
object is maintaining is if there’s a public method or property that reveals it.
As an example, imagine an object whose job is to implement a stack — it might be an
instance of a Stack class. A stack is a data structure that maintains a set of data in
LIFO order (last in, first out). It responds to just two messages: push and pop. Push
means to add a given piece of data to the set. Pop means to remove from the set the
piece of data that was most recently pushed and hand it out. It’s like a stack of plates:
plates are placed onto the top of the stack or removed from the top of the stack one
by one, so the first plate to go onto the stack can’t be retrieved until all other subse‐
quently added plates have been removed (Figure 1-3).
The stack object illustrates encapsulation of functionality because the outside world
knows nothing of how the stack is actually implemented. It might be an array, it
might be a linked list, it might be any of a number of other implementations. But a
client object — an object that actually sends a push or pop message to the stack object
— knows nothing of this and cares less, provided the stack object adheres to its con‐
tract of behaving like a stack. This is also good for the programmer, who can, as the
Design | 23
Figure 1-3. A stack
program develops, safely substitute one implementation for another without harming
the vast machinery of the program as a whole.
The stack object illustrates maintenance of state because it isn’t just the gateway to the
stack data — it is the stack data. Other objects can get access to that data, but only by
virtue of having access to the stack object itself, and only in the manner that the stack
object permits. The stack data is effectively inside the stack object; no one else can see
it. All that another object can do is push or pop.
The sum total of messages that each object type is eligible to be sent by other objects
— its API (application programming interface) — is like a list or menu of things you
can ask this type of object to do. Your object types divide up your code; their APIs
form the basis of communication between those divisions. The same is true of objects
that you didn’t design. Apple’s Cocoa documentation consists largely of lists of object
APIs. For example, to know what messages you can send to an NSString instance,
you’d start by studying the NSString class documentation. That page is really just a
big list of properties and methods, so it tells you what an NSString object can do —
24 | Chapter 1: The Architecture of Swift
and thus constitutes the bulk of what you need to know in order to use NSStrings in
your program.
Instance Creation, Scope, and Lifetime
The important moment-to-moment entities in a Swift program are mostly instances.
Object types define what kinds of instances there can be and how each kind of
instance behaves. But the actual instances of those types are the state-carrying indi‐
vidual “things” that the program is all about, and instance methods and properties are
messages that can be sent to instances. So there need to be instances in order for the
program to do anything.
By default, however, there are no instances! Looking back at Example 1-1, we defined
some object types, but we made no instances of them. If we were to run this program,
our object types would exist from the get-go, but that’s all that would exist. We’ve cre‐
ated a world of pure potentiality — some types of object that might exist. In that
world, nothing would actually happen.
Instances do not come into being by magic. You have to instantiate a type in order to
obtain an instance. Much of the action of your program, therefore, will consist of
instantiating types. And of course you will want those instances to persist, so you will
also assign each newly created instance to a variable as a shoebox to hold it, name it,
and give it a lifetime. The instance will persist according to the lifetime of the variable
that refers to it. And the instance will be visible to other instances according to the
scope of the variable that refers to it.
Much of the art of object-based programming involves giving instances a sufficient
lifetime and making them visible to one another. You will often put an instance into a
particular shoebox — assigning it to a particular variable, declared at a certain scope
— exactly so that, thanks to the rules of variable lifetime and scope, this instance will
persist long enough to keep being useful to your program while it will still be needed,
and so that other code can get a reference to this instance and talk to it later.
Planning how you’re going to create instances, and working out the lifetimes and
communication between those instances, may sound daunting. Fortunately, in real
life, when you’re programming iOS, the Cocoa framework itself will provide an initial
scaffolding for you. Before you write a single line of code, the framework ensures that
your app, as it launches, is given some instances that will persist for the lifetime of the
app, providing the basis of your app’s visible interface and giving you an initial place
to put your own instances and give them sufficiently long lifetimes.
Summary and Conclusion
As we imagine constructing an object-based program for performing a particular
task, we bear in mind the nature of objects. There are types and instances. A type is a
Design | 25
set of methods describing what all instances of that type can do (encapsulation of
functionality). Instances of the same type differ only in the value of their properties
(maintenance of state). We plan accordingly. Objects are an organizational tool, a set
of boxes for encapsulating the code that accomplishes a particular task. They are also
a conceptual tool. The programmer, being forced to think in terms of discrete objects,
must divide the goals and behaviors of the program into discrete tasks, each task
being assigned to an appropriate object.
At the same time, no object is an island. Objects can cooperate with one another,
namely by communicating with one another — that is, by sending messages to one
another. The ways in which appropriate lines of communication can be arranged are
innumerable. Coming up with an appropriate arrangement — an architecture — for
the cooperative and orderly relationship between objects is one of the most challeng‐
ing aspects of object-based programming. In iOS programming, you get a boost from
the Cocoa framework, which provides an initial set of object types and a practical
basic architectural scaffolding.
Using object-based programming effectively to make a program do what you want it
to do while keeping it clear and maintainable is itself an art; your abilities will
improve with experience. Eventually, you may want to do some further reading on
effective planning and construction of the architecture of an object-based program. I
recommend in particular two classic, favorite books. Refactoring, by Martin Fowler
(Addison-Wesley, 1999), describes why you might need to rearrange what methods
belong to what classes (and how to conquer your fear of doing so). Design Patterns,
by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (also known as
“the Gang of Four”), is the bible on architecting object-based programs, listing all the
ways you can arrange objects with the right powers and the right knowledge of one
another (Addison-Wesley, 1994).
26 | Chapter 1: The Architecture of Swift
Exploring the Variety of Random
Documents with Different Content
Five days afterwards, on the 26th, there was a recurrence of the
typhoon, which the Nemesis rode out very easily in the Typa
anchorage at Macao; but it was not so severe as the first one, and
comparatively little injury was caused by it. There is reason to
believe also, that, had all the ships at Hong-Kong been moored in
proper berths, and early precautions taken, before the
commencement of the first typhoon, the danger and the damage
inflicted would have been much less severe.
No time was lost in refitting the ships, and preparations were now
hastened for the advance of our forces upon Amoy, and for pushing
on our operations further northward, while the favourable season
lasted. Sir Gordon Bremer had returned from Calcutta, in the Queen
steamer, on the 18th of June, having been invested with the
functions of joint-plenipotentiary, in conjunction with Captain Elliot.
This high honour was, however, of short duration; for, on the 9th of
August, Sir Henry Pottinger arrived from England, via Bombay,
having been appointed sole plenipotentiary and chief-superintendent
of trade in China: he was accompanied by Vice-Admiral Sir William
Parker, by whom all the subsequent naval operations were
conducted.
CHAPTER XXVI.
At the end of July, the H.C. steamer Phlegethon, Lieut. M'Cleverty,
nearly the exact counterpart of the Nemesis, arrived at Hong-Kong,
bringing the intelligence that Captain Elliot's treaty of Chuenpee had
been disapproved of by the home government, and that Sir Henry
Pottinger had been appointed to succeed him, as sole
plenipotentiary. Shortly before this, also, her Majesty's 55th regiment
had arrived from Calcutta, and everything indicated that a
movement upon Amoy would take place as soon as possible, after
the expected arrival of Sir Henry Pottinger as plenipotentiary, and Sir
William Parker as admiral. The season for active operations was
already advanced, and even for the sake of the health of the troops,
it was the anxious wish of all the officers that a change of some sort
or other might speedily take place.
In the afternoon of the 10th of August, the arrival of the H.C.
steamer Sesostris, from Bombay, in the Macao roads, was
announced, and great was the joy of every one when it was made
known that both Sir Henry Pottinger and Sir William Parker were on
board. They had come from London in the wonderfully short period
of sixty-seven days, ten of which had been spent in Bombay.
At daylight next morning, the Nemesis went out to convey these
high functionaries from the Sesostris, in the roads, to the town of
Macao, where they were received with every demonstration of
respect, under a salute from the Portuguese forts. A conference was
held in the course of the morning, between Captain Elliot and Sir
Henry Pottinger, together with the Admiral and Sir Hugh Gough.
Energetic measures appeared to be at once resolved on. Sir William
Parker went over to visit the fleet at Hong-Kong, and as soon as
visits of ceremony had been exchanged between the new
plenipotentiary and the Portuguese authorities, Sir Henry Pottinger
lost no time in publishing the notification of his appointment, as
minister extraordinary and sole plenipotentiary, and also as chief
superintendent of trade in China.
In order to communicate officially to the Chinese authorities the fact
of his arrival, and the nature of his powers, Sir Henry now
despatched his secretary, Major Malcolm, to Canton, as the bearer of
letters to the provincial government. The Nemesis was, as usual,
employed to carry the officers up the river. No little sensation was
created among the Chinese officials by the announcement which was
now made to them. They therefore resolved to welcome the
plenipotentiary with all ceremony; and probably, also, in the hope of
being able to form some estimate of his character, they despatched
the prefect of the city, or kwang-chow-foo, on the 18th, to Macao,
with a numerous retinue. He landed at Macao, upon the Praya
Grande, near the governor's palace, attended by a great number of
followers, and proceeded in state to the residence of the
plenipotentiary, thinking, no doubt, that he was conferring a great
honour upon his Excellency, and that he would accordingly be
received with every mark of distinction. Alas, how are the mighty
fallen! The ceremonious prefect was not even received. He, who had
hitherto been courted as an officer of distinction, and had been the
medium of communication, and in some sort the ambassador,
between the high Chinese authorities and Captain Elliot, was now
absolutely rejected. Sir Henry Pottinger, acting with an intimate
knowledge of the Oriental character, and fully impressed with the
high duties he was called upon to perform, and the high station he
had to maintain as her Majesty's representative, declined to receive
or hold any direct intercourse with an officer inferior to himself in
rank and responsibility, and still less with one of comparatively
inferior grade, such as the Prefect of Canton.
Major Malcolm, the secretary of legation, was, however, deputed to
receive the prefect; and, after a short interview, the would-be great
man withdrew, and returned in some dismay to Canton, to report
the circumstances to his superiors. The sensation created by this
little characteristic incident was very remarkable. It became the
subject of conversation in every quarter, and tended to awaken
much greater respect for the dignity of the new plenipotentiary. The
same cautious and dignified bearing was maintained with the
greatest advantage throughout the whole of our subsequent
proceedings.
At Hong-Kong, the most active preparations were now being made
for the immediate departure of the expedition. Excellent
arrangements were introduced by Sir William Parker for the proper
guidance of the fleet, and especially for the distribution and
management of the numerous transports and store-ships. The
advantage of this systematic regularity soon became evident; and it
is deserving of notice that, from this period to the close of the war,
the transport service was conducted with the utmost regularity and
efficiency, in spite of the endless difficulties arising out of our
imperfect knowledge of the coast of China, and the inaccuracy of
most of the charts. Add to this, that owing to sickness and other
causes, the transports were often under-manned, and had
frequently the most arduous duties to perform.
By a general order of the 19th of August, issued only nine days after
the arrival of the admiral, the fleet was directed to be ready to put to
sea at daylight on the 21st. It was to be formed in three divisions:
the centre commanded by Captain Herbert, in the Blenheim, assisted
by Commander Clarke, of the Columbine; the starboard division,
under Captain Bourchier, in the Blonde, assisted by Commander
Gifford, in the Cruiser; while the second, or port division, was placed
under Captain Smith, of the Druid, assisted by Commander Anson,
of the Pylades.
The whole fleet consisted of thirty-six sail, including transports—
namely, two line-of-battle ships, the Wellesley and the Blenheim;
seven other ships of war—namely, the Modeste, Druid, Columbine,
Blonde, Pylades, Cruiser, and Algerine; the Rattlesnake troop-ship,
and the Bentinck surveying vessel; four steamers belonging to the
East India Company—namely, the Queen, Phlegethon, Nemesis, and
Sesostris; and twenty-one hired transports and store-ships, most of
them of large size, several of not less than a thousand tons burden.
The force stationed in the neighbourhood of the Canton river
comprised five or six vessels of war, including the Herald and
Alligator, and was under the command of Captain Nias, senior officer.
Early on the morning of the 21st, the fleet got under weigh. Sir
Henry Pottinger came over from Macao, in The Queen, on that day,
just as the fleet had sailed; and, as he stopped some time at Hong-
Hong to inspect the place, and examine the various arrangements
which had already been made, he did not join the admiral until the
following day. The general rendezvous, in case of separation, was to
be Chapel Island, not far from Amoy. The weather was extremely
favourable during the whole passage up, and, on the 25th, the
whole squadron reached the outer harbour of Amoy, having
preserved the order of sailing remarkably well throughout.
The late plenipotentiaries, Captain Elliot and Sir Gordon Bremer,
sailed from Hong-Kong, and finally took leave of China, three days
after the departure of the expedition, on board the Atalanta steamer,
which had become completely knocked up by her work in the Canton
river. Their intention was to proceed as quickly as possible to
England, by way of Bombay.
The distance of Amoy from Hong-Kong is scarcely three hundred
miles, and there were many good grounds for making it the first
point of attack, as the expedition proceeded northward. It could not
be doubted that the capture of this flourishing commercial city would
be seriously felt by the Chinese government. The authorities had,
within the last twelve months, spent enormous sums of money and
incredible labour in the construction of batteries, which they deemed
impregnable, and which were certainly capable of being stoutly
defended.
The harbour of Amoy is situated in the south-western corner of an
island of the same name, which, together with another called
Quemoy, occupies a considerable portion of a large bay, in which,
however, there are also numerous smaller islands. Of these, the
most interesting, in connexion with our present subject, is that of
Kolingsoo, which is separated from Amoy by a narrow passage,
leading directly up to the harbour. In fact, the possession of this
island, which we still retain, gives us the complete command of
Amoy itself, or rather of its town and suburbs.
The scenery within the bay and about the town of Amoy is
exceedingly picturesque, the appearance of the country being very
mountainous and striking. Several considerable rivers pour their
waters into the bay, and facilitate the communications with the
interior of the country. The superiority of the harbour much
exceeded the expectations of the officers.
The town of Amoy, although possessed of great commercial
importance, and very wealthy, is by no means a first-class city—it
ranks, indeed, only as a principal third-class town—but its
inhabitants are exceedingly enterprising and intelligent, and are
remarkable for a certain disposition for emigration and colonization,
as well as for their love of commerce. They were the principal
colonizers of the flourishing island of Formosa, which lies opposite
Amoy, extending itself along the coast for a distance of little less
than two hundred miles; and they are to be found in great numbers
in more remote islands, subject even to foreign dominion, such as
Java, Singapore, Manilla, &c.
The city and suburbs of Amoy can hardly be less than eight or ten
miles in circumference, and they are in a great degree commanded
by a fortified hill or citadel in the rear, which, however, is again
commanded (as is very commonly the case in China) by unfortified
heights beyond it to the eastward. The suburbs, or outer town, are
separated from the principal or inner town by a line of steep, rocky
hills, which run transversely down to the beach; but a paved road or
narrow causeway leads into the city, through a pass which is
protected by a covered gateway at its summit. As there is, therefore,
what may be called a double town, so is there also a sort of double
harbour—the outer one running along the face of the outer town,
and the inner one extending along the front of the principal town,
and joining a large estuary, which runs deep into the island across
its centre, and skirts the northern side of the city. In this manner,
nearly two-thirds of the city of Amoy are washed by the sea. In fact,
it stands upon a corner or tongue of land, having a line of bold
mountains in its rear and on its flank. The walls are castellated at
top, and vary in height, according to the nature of the ground, from
twenty to thirty feet. There are also, as in other places, four principal
gates, having each an outwork or outer wall, with a court or open
space between them, and a second gate leading from this, and
placed at right angles to the inner one, so that the approach to it
from the outside is commanded by the principal wall of the town.
The citadel of Amoy was afterwards found to contain a large supply
of military accoutrements—ginjals, matchlocks, swords, shields, and
spears of all kinds; there was also an immense quantity of
gunpowder, and materials for making it; in short, there was every
reason to believe that Amoy had been made use of as the great
military depôt of the province.
It is impossible to form even a tolerable estimate of the number of
troops collected for the defence of the place, but the different
accounts which were received varied from six thousand to eight or
ten thousand men. It was also known that the high officers of the
province had come down to Amoy purposely to encourage the
defence, and to witness, as they hoped, the utter discomfiture of the
barbarians. It was, however, upon their newly-constructed works
that they placed their great reliance.
Numerous forts and field-works had been erected upon nearly all the
smaller islands which stretch across the mouth of the great bay; and
upon the island of Amoy itself a succession of batteries and field-
works had been built to command the approach to the town. The
principal of these was a long stone battery, well built of granite,
faced with earth, extending along the shore nearly up to the suburbs
of the city, and designed to command the passage to the harbour. It
presented a line of guns a full mile in length, the embrasures being
covered with large slabs of stone protected by earth heaped upon
them, and mounting no less than ninety-six guns. In the rear of this
battery there was a range of steep, rocky heights, up the side of
which the Chinese had carried a strong castellated wall to serve as a
flanking defence to the battery.
Still further to defend the approaches to the city, they had also
strongly fortified the little island of Kolingsoo, between which and
Amoy the passage is not more than six hundred yards across; this
island is, in fact, the key of Amoy, and was retained in our
possession when the city and the island of Amoy were restored to
the Chinese. At that time the Chinese had already mounted upon the
works, either completed or in progress, no less than seventy-six
guns. Indeed they had spared no labour to endeavour to render
Amoy capable of easy defence; although, from want of skill and
discipline, the resistance which they offered was comparatively
trifling. If the number of guns alone could indicate the strength of a
place, the Chinese might have had some grounds for confidence; for,
as Sir Hugh Gough remarked, "every island, every projecting
headland whence guns could be made to bear, was occupied and
strongly armed." In fact, there were altogether not less than five
hundred guns captured at Amoy and the adjacent islands.
Early on the morning of the 26th of August, everything was in
readiness for the projected attack. The captains and commanders
repaired on board the flag-ship for orders; the steamers were all
smoking and blowing off their spare steam, and the officers were all
anxiously looking for the expected signal to stand in and engage the
batteries. Before active operations commenced, however, it was
thought right to make a reconnoissance of the defences which were
to be attacked. With this view Sir Hugh Gough, Sir William Parker,
and the plenipotentiary, stood in on board the Phlegethon, and were
able to approach sufficiently close to the works to observe all that
was necessary, without having a single shot fired at them.
In the meantime a messenger, supposed to be a Chinese merchant,
came off from the town, under a flag of truce, requesting to know
the object of the visit of so large and formidable a squadron. The
answer to this question was simple enough, and was sent in the
name of the plenipotentiary, the general, and the admiral, to the
effect that "they required that the demands made last year at
Tientsin, (near Pekin,) by Captain Elliot, should be complied with;
and that hostile measures would, if necessary, be adopted to enforce
them. Nevertheless, that as the plenipotentiary and the
commanders-in-chief were moved by compassionate feelings, and
were unwilling to cause the death of so many officers and soldiers as
must perish, they were willing to allow all the officers and troops in
the town to retire with their personal arms and baggage, in order to
save the people from being hurt, upon condition that the town and
fortifications of Amoy should be at once delivered into the hands of
the British forces, to be held for the present by them." A white flag
was to be exhibited from the fortifications, if these terms were
acceded to; otherwise, hostilities would commence. As might be
expected, the white flag was not displayed.
The morning was very hot and sultry; but about one o'clock a
steady, favourable breeze set in, and the squadron got under weigh.
The plan was, to make a simultaneous attack upon all the batteries
at once, both against those upon Amoy and those upon Kolingsoo.
The troops were also to be landed, with the object of taking the
batteries in the rear; and the Nemesis and Phlegethon steamers
were to be employed to convey them to the appointed place of
debarkation.
The ships were likely to bear the chief brunt of the engagement; but
Sir Hugh Gough made every disposition for the employment of the
land forces, and his general order, issued just before the attack was
to take place, deserves especial notice. He directed his remarks very
strongly to the question of plundering; and observed, that "as Amoy
was a large commercial port, and there had once been an English
factory there, it was highly important that no act should be
committed which could tend to embarrass our future friendly
intercourse. The government and the military were to be overcome,
and public property taken possession of, under certain instructions,
but private property was to be held inviolable; and that which in
England," observed the general, "obtains the name of robbery,
deserves no better name in China." The camp followers were made
liable to be put to death for plundering; and orders were issued to
punish on the spot any man straggling from his corps.
This alone will suffice to point out that the expedition was very far
from possessing that buccaneering character which some persons,
particularly foreigners, attempted to cast upon it. Indeed, it may
safely be asserted, that war was never carried on with so little
infliction of suffering upon the people generally as in China.
Generally speaking, the people soon learned to appreciate our
motives; and unless prevented by their own officers, they commonly
shewed a friendly, or at all events a neutral feeling towards us.
Besides the English, the privilege of trading at Amoy was formerly
held by the Spanish also; and, at no very remote period, a regular
intercourse was kept up between Amoy and the Spanish colony of
Manilla.
It was probable that the nature of the country round Amoy would
render brigade movements inadmissible; but the troops were to be
prepared to form in three brigades, if necessary. The men were to
land in jackets, caps, and coats folded; and were to carry, each man,
one day's cooked provisions. The artillery were to be in readiness to
land their light, mountain guns.
About half-past one, the attack commenced on our side; but the
Chinese had already begun the engagement, by firing occasional
shots at our ships, as they proceeded with a steady and favourable
breeze to their respective stations. The Sesostris and Queen
steamers led in; the former commencing the action, but receiving a
heavy fire before she returned it. The line-of-battle ships, Wellesley
and Blenheim, under Captains Maitland and Herbert, proceeded to
the extremity of the long stone battery, nearest the suburbs, where
they anchored by the stern, about half-past two P.M., within four
hundred yards of the works, and at once opened a heavy fire upon
the principal battery.
The next in order along the front of these works, from the suburbs
towards the outer extremity, were the Pylades, Columbine, Cruiser,
and Algerine. Simultaneously with this attack upon Amoy, the
Blonde, Druid, and Modeste, reached their allotted stations, against
the works of Kolingsoo; but, owing to the shallowness of the water,
they were boldly carried on, in little more than their own draught.
The roar of the artillery on every side, echoed by the mountains
around, was now terrific; and in one hour and twenty minutes the
three principal batteries on Kolingsoo were silenced, and the marines
under Captain Ellis, about one hundred and seventy in number, were
landed on that island, and took possession of the heights in the rear,
without any loss. Three companies of the 26th regiment had also
been appointed to this service, but the distance of the transports
only permitted a small detachment of them, under Major Johnstone,
to land in time to assist in clearing the batteries. The small
detachment of the Royal Artillery, under Lieut. the Hon. R. E.
Spencer, were actively employed on board the Blonde, during the
attack.
While these operations were being carried on against the batteries
on Kolingsoo, and against the long battery on Amoy, the Phlegethon
and Nemesis were speedily brought up with the troops ready to
land. The Nemesis had taken on board the general and his staff,
together with the 18th Royal Irish, under Colonel Adams; and had
also to tow up a number of boats, with the sappers and miners,
followers, &c. Considerable delay was therefore occasioned by
having to run up to the different transports to embark detachments,
and also to pick up the boats; and it was not until half-past three
that the Nemesis could get into action. She then opened fire at the
long battery with her heavy guns and rockets, as she approached
the lower angle of the fort for the purpose of landing the troops.
It was just about this time, that as the Phlegethon was also running
up towards the battery, a boat was despatched by Lieut. M'Cleverty,
in which Lieut. Crawford volunteered his services to capture a small
outwork upon a hill, very near the beach; and it was here that the
British flag was first displayed upon the enemy's works, on that day,
with three cheers from the steamers.
About a quarter before four, the general landed upon the beach,
near the flank of the great battery, with the 18th and 49th
regiments, which were carried in by the Nemesis and Phlegethon
steamers. The disembarkation was conducted by Commander
Giffard, of the Cruiser. The 18th was directed to escalade the
castellated wall which flanked the battery; and, as already described,
ran up the hill-side from the beach, nearly at right angles to it. At
the same time, the 49th were to move along the beach towards the
lower angle of the battery, and either get over it at its sea-face, or
force their way through the embrasures.
A smart fire was kept up from the Nemesis, to cover the landing and
advance of the troops; and Capt. Hall himself, anxious to take an
active part in every operation, pushed off from the steamer, in the
pinnace manned and armed, accompanied by the unfortunate Mr.
Gully, who, as an old and brave friend, volunteered to go with him.
This was the same gentleman who afterwards fell a victim to the
rapacity and cruelty of the Chinese authorities on the island of
Formosa, upon which he had the misfortune to be wrecked, and,
after seven months' imprisonment and cruel treatment, was at
length executed, together with nearly all his companions.
As soon as Capt. Hall and his friend had landed with the pinnace's
crew, they joined the advanced guard of the 18th, under Major
Tomlinson and Lieut. Murray, who were advancing towards the lower
end of the castellated wall. The Chinese opened a smart fire of
ginjals and matchlocks as they approached, which was returned by
the advancing party, who took advantage of the numerous little
hillocks and tombs which lay in their way, to shelter themselves
while they reloaded.
The Chinese, finding their enemy pressing up towards the wall, and
being already bewildered by the admirable firing of the ships, now
began to slacken their fire. The 18th rushed for the lower end of the
wall, while the party from the Nemesis made a dash at its flank,
some way higher up, near a gateway, where the wall appeared less
elevated and more accessible. They had, however, brought no
scaling-ladders, and, in order to get over the wall, the men were
obliged to be lifted up on each other's backs. In this way Captain
Hall managed to get first upon the top of the wall, and instantly
waved the British flag (which on such occasions he always carried
with him in his pocket) in token of triumph. Others soon followed;
and the Chinese, the moment they saw their enemies upon the
walls, fired two or three random shots, and fled. At this time also the
18th got over the wall lower down, while the 49th forced their way
through the embrasures, just at the angle of the sea-face of the
great battery. The fire of the ships had not yet ceased, when the
party from the Nemesis got down into the body of the fort, and
several of our large shot fell close around them.
A very short distance in advance they now observed that two
Chinese officers of high rank, mounted on horseback, were
endeavouring to make their escape, surrounded by a numerous
body-guard, or retinue. The opportunity for trying to take an
important prisoner was a tempting one; and Captain Hall, little
thinking how few of his own men were near him, and carried away
by the impulse of the moment, rushed headlong upon the Chinese
soldiers in front of him, firing off his pistols at the two principal
officers. Only two of his own men were near him at the moment; so
that one of the inferior Chinese officers, seeing the disparity, rallied a
few of his men, and suddenly faced about, with a view to cut them
off. A personal encounter now took place with the Chinese officer,
who was a remarkably fine young man, bearing the white button.
The long sword, however, soon had the advantage over the Chinese
short one, even putting aside personal prowess, and the mandarin
fell severely wounded in the arm. He was immediately disarmed, and
his cap and button, together with his sword, were taken from him as
trophies. Several other soldiers now came up, to endeavour to
rescue their officer, who got up and tried to escape, but another
wound in the leg soon brought him down again, and made the other
Chinamen halt.
By this time, Captain Hall and his two men were nearly surrounded,
and were compelled to fight their way back again towards their
comrades, who were coming up to their aid. One of the two seamen
received a severe wound in the groin from the thrust of a spear, but
the others got off without any injury. The young wounded mandarin
was at last safely carried off by his comrades.
The Chinese were now in full flight in every direction, followed by
the 18th, 49th, and a party of small-arm men, who were landed
from the Wellesley and Blenheim, some way up the sea-face of the
fort, under Commander Fletcher and other officers of those ships.
The fort was soon completely in our possession. During all the
operations of this day, Sir Henry Pottinger and suite were with the
admiral on board the Wellesley.
On examining the sea-face of the battery, it was impossible not to be
struck with the amazing solidity of the wall. It was composed of
hewn granite, faced outside with earth, and of such strength, that
the heavy firing of two line-of-battle ships against it, at the distance
of only four hundred yards, had made very little impression; indeed,
it might be said to be shot-proof. The embrasures were something
like low port-holes, covered with stone and earth, and in the space
between them were sheds, or a sort of temporary watch-boxes, in
which was found a quantity of arms of every kind, clothes, half-
cooked food, and also opium, with the common pipes used for
smoking it. A horse also was found. The guns were many of them
very ill-mounted, and in general the carriages were badly contrived,
and often defective. In some places you saw bags of sand placed
upon the top of the guns, to prevent them from jumping out of the
carriages altogether. The fort had evidently been armed hastily.
Several high Chinese officers fell during this day; some probably by
their own hands. One of them very quietly rushed into the water and
drowned himself, although, in the report of the affair to the emperor,
it was afterwards stated that he "rushed on to drive back the
assailants as they landed, and fell into the water and died." This
officer was the Chinese commodore, who commanded in the
absence of the admiral. This officer had left the port just before our
arrival, (boasting that he was going to meet the barbarians,) and,
having sailed northward, could not get back again, owing to the
contrary wind.
Before five o'clock, the whole of the outer defences of Amoy were in
our possession. The Blonde and Modeste, as soon as they had
silenced the batteries on Kolingsoo, with the assistance of the Druid,
had pushed on into the inner harbour, and captured twenty-six war-
junks, mounting not less than one hundred and twenty-eight guns;
they were nearly ready for sea, but were deserted by their crews. A
large building-yard was discovered, with an immense quantity of
timber collected in it; and there was a good-sized frigate-junk, of
about three hundred tons, in course of building, in a regular dry
dock, something after the European model; they had evidently made
a great step in advance in the art of ship-building; indeed, the longer
the war lasted, the more the Chinese found themselves led on, by
the "impulse of necessity," to attempt great changes, and, in many
respects, improvements, not only in their vessels, but in their warlike
weapons, and other matters relating to the art of defence.
The Nemesis, in running along the shore to avoid the swell which
was setting in, unexpectedly found herself within a circular patch of
coral rock, which was not visible above the surface. Several fruitless
attempts were made to extricate her from this curious position, but
the entrance by which she had got into it could not again be found;
but her draught of water being very small, it was thought likely she
would be able to force her way over the reef without suffering much
damage to her iron hull, and she dashed at it at half speed. The
blow, however, was more severe than was expected; the vessel
bounded completely over the reef; but the sharp coral rock cut
completely through her bottom, making a considerable leak in the
engine-room. This was fortunately stopped from the inside without
much difficulty, and no further notice was taken of it until some time
afterwards, when she arrived at Chusan, where the damage was
substantially repaired.
In the meantime, Sir Hugh Gough pushed on without delay, to
occupy a chain of steep, rocky hills, which, running transversely
down to the beach, lay between the great fort and the town, so as
to intercept the view of the latter. A strong body of the Chinese
seemed disposed to defend this position, which was naturally of
great strength, and completely commanded the approach to the city.
Immediate advantage was to be taken of the prevailing panic; and
the 18th and 49th regiments being directed to advance partly up a
steep gorge, and partly by a more circuitous road leading round the
hills, soon made themselves masters of the heights overlooking the
city. The Chinese retreated before them as soon as they had fired off
their guns and matchlocks. Our troops bivouacked for the night upon
the positions they occupied; but they might have been a good deal
harassed by the Chinese, if the latter had taken advantage of the
rocky, broken character of the ground, to dispute their further
advance. The night was bitterly cold upon the heights.
At daylight a reconnoissance was made, and it was soon discovered
that little resistance was to be expected. Great confusion and bustle
were apparent in all directions; hundreds of the inhabitants were
hurrying out of the northern gate, carrying with them their most
valuable property; in fact, there was evidently a general panic.
Without loss of time, therefore, the 18th, supported by the 49th,
were ordered to march down towards the city in the direction of the
eastern gate, which was the nearest, while Captain Cotton, the
commanding engineer, was directed to examine carefully the
approaches to the gate itself.
The advanced party of the 18th, on arriving at the gate, found that
there was no preparation for resistance, and soon scaled the walls
by means of some ladders which were very opportunely found not
far from the gate. Heaps of rubbish, and sacks full of earth and
sand, were found piled up inside against the gate, so that some time
was required to get it open. It was now discovered that the
authorities and all the soldiers had abandoned the town, leaving
everything in the utmost disorder, so that the only protection which
the more respectable and peaceably-inclined inhabitants had to look
for, from the violence and plundering of their own rabble, was from
the presence of our own troops, and the military government of the
city by the victorious captors. Already the mob had begun to ransack
some of the public establishments before we found out where they
were situated; and it was afterwards discovered that a good deal of
treasure must have been carried away by the thieves and vagabonds
of the town. A number of men were found carrying out of the gates
something having the appearance of common logs of wood; and it
was not suspected, until too late, that these logs were hollowed out,
and filled with Sycee silver, a very ingenious contrivance to escape
detection. A small quantity of treasure was found in one of the large
buildings, supposed to be the office of the commandant, which was
occupied by the sappers and miners.
Most of the public offices were large and roomy buildings, affording
good accommodation for a whole regiment of soldiers. The pile of
buildings belonging to the admiral's department was assigned to the
18th and the staff, being within the walled town; while the 49th
were quartered in the outer town, in a large building belonging to
the office of the Intendant of Circuit. The 55th occupied an extensive
range of buildings belonging to the Prefect of Amoy; the artillery
retaining possession of a commanding position overlooking both the
city and the outer town.
Late in the day, and also on the following morning, Sir Henry
Pottinger and Sir William Parker landed, to take a view of the town;
but, after visiting the principal buildings, they returned on board
ship.
Numerous patrols were found necessary, by day and night, in order
to preserve quiet in the public streets, and to check the boldness
and rapacity of the swarms of Chinese thieves and rogues, who
hovered about like a raging pestilence in every part of the city, and
crowded in from the country the moment the respectable inhabitants
left the town. The inhabitants themselves were, in many instances,
afraid even to defend their own property, or to aid our troops in
restoring order and regularity; they dreaded the probable imputation
of having traitorously aided the foreigners, and the fear of extortion
and punishment from their own authorities, at some future period,
served to disorganize the whole community. In vain did Sir Hugh
Gough appeal to the more respectable merchants and householders
to aid him in protecting property; all that he could get from them
was empty promises, of which they were very liberal, but from which
no good result followed. Even within the citadel, or walled town, it
was with the utmost difficulty that the daring thieves and vagabonds
could be kept in check; and hardly could even a single Chinaman be
induced to point out to the guards at the gate the real bonâ fide
owners of houses or property, in order that they might be allowed
free egress and ingress.
The injury which the inhabitants of many Chinese towns suffered
during our operations must not be estimated by the actual damage
(generally trifling) done by our fire, or by the presence of our troops.
In most instances, even before hostilities commenced, the presence
of the Chinese troops, who were marched in probably from several
distant provinces, became almost a scourge to the inhabitants; and
afterwards, when a town was taken, and the local government
disorganized, much greater damage was done to the property of the
people by the low mob of plunderers, than would, under any
circumstances, have been allowed by our own victorious soldiers;
indeed, some instances occurred in which the former were shot by
our guards, rather than desist from their evil doings.
Our men often resisted temptations of no ordinary kind; houses
were found abandoned, property left unprotected, shops open, and
goods strewed about; and even the abominable spirit, samshu,
(distilled from rice,) was sometimes almost purposely placed in their
way. The instances of misconduct were few, even under these
peculiar circumstances.
Among other discoveries was one calculated to corroborate at first
sight the notion of the prevalence of infanticide among the Chinese.
In a large tank near a public building, by some supposed to have
been an hospital, were found the dead bodies of several young
infants which had been drowned, having been thrown in, sewn up in
pieces of mat. But there was nothing to determine whether the
horrid deed was done out of fear that violence might be offered to
the women and children, or whether it was really an instance of the
practice of infanticide, which has been said to prevail in China to a
much greater extent than it really does. The former explanation may
possibly in this instance, as in some later ones, be the true one.
The interior of the island of Amoy was not occupied, or even
examined, for it was feared by the general that the presence of our
troops would so much alarm the respectable and influential
inhabitants, that the whole place would be given up to the rapacity
and lawlessness of the innumerable miscreants who watched for
every opportunity of letting loose all their bad propensities; but the
Nemesis, accompanied by the Algerine, and having in tow the launch
and pinnace of the Blonde, was ordered to steam round the island,
and search for war-junks. None, however, were found.
The island of Kolingsoo appeared so completely to command the
harbour and approach to Amoy, that the occupation of that position
only was calculated to answer every good purpose, without the
necessity for the retention of Amoy.
It was the opinion of Sir Henry Pottinger, in which the general and
the admiral perfectly coincided, that no measures should be taken
for the permanent occupation of the city, and that a small garrison
only should be left at Kolingsoo, while the remainder of the
expedition should move further northward with the least possible
delay. It was necessary, however, to wait a day or two for favourable
winds, and measures were taken for the destruction of the
numerous works which had been constructed upon the outer islands.
The Nemesis was employed on this important service on the 30th
and 31st. Having been joined by two launches and other boats, with
a party of seamen and marines from the Wellesley, Blenheim, and
Druid, under Commander Fletcher, she proceeded to destroy some
forts and guns, principally on the south-west side of the bay, all of
which had been abandoned by the Chinese. On this occasion, five
forts or field-works and forty-two guns were taken possession of and
destroyed, and on the following day several others of the same
description were also disabled. A body of Chinese soldiers, who
shewed themselves near a small fort on the island of Quemoy, at the
eastern entrance of the bay, were dispersed, and several guns,
matchlocks, ginjals, &c., together with a quantity of gunpowder,
were destroyed. Altogether seventy-seven guns and four forts were
destroyed in this day's work, and the admiral publicly spoke of the
"very commendable zeal" which had been displayed.
At Amoy, for the first time, the so-called tiger soldiers shewed
themselves—that is, men dressed up in yellow-coloured clothes, with
black spots or stripes upon them, and a covering for the head,
intended to be a rude representation of a tiger's head, supposed to
look very fierce, and to strike terror into the minds of the enemy.
The island of Kolingsoo, which had been retained in our possession
ever since its capture, deserves a few remarks. It is about a mile and
a half in length, and about three quarters of a mile broad, but is very
irregular in its shape. It principally consists of rocky broken ground,
the greater part of which is barren, but interspersed with
unwholesome rice-grounds, which have contributed to render the
place extremely unhealthy; indeed at one period the mortality
among the troops stationed there was dreadful, scarcely even a
single officer having escaped sickness, which proved fatal to many.
The Chinese, however, seemed to have suffered little from it, for
there were several neat and even elegant country-houses upon the
island, ornamented with handsome carved wood-work, &c. It
seemed to have been used as a place of retirement for some of the
wealthier citizens of Amoy, and our retention of a place so
conveniently situated for giving us the command of the harbour and
trade of the city was a source of great annoyance, both to the
authorities and to the inhabitants.
For a considerable time, very little communication was kept up with
the town, and it was scarcely safe to venture into it; but since the
peace, every disposition has been shewn to receive us in a friendly
manner, and the knowledge which many of the Chinese merchants
have acquired of our character and habits, by trading with
Singapore, will tend materially to facilitate our future commercial
intercourse.
Several American missionaries have resided at Kolingsoo, and
without doubt will, at no distant period, succeed in winning the
attention and good-will of many of the inhabitants of Amoy. A
boundless field has at length been opened for missionary enterprise
in the benighted empire of China; for, although it cannot be said that
the country has been made completely accessible to the foreigner,
still the hostility of the government has been materially modified.
It rests with the Christian nations to profit as Christians, by the
opportunities which cannot fail to offer. Among a people so fond of
reading and thinking, and so given to study and inquiry as the
Chinese generally are, the best possible results are to be expected
from the judicious teaching of Christianity, and, above all, of
Christian practices. If China is really to be opened, it is to be
effected by missionary enterprise cautiously and judiciously, and,
above all, not too hastily applied.
The most valuable of all aids to these undertakings, is that of
medical knowledge, which may be considered as almost
indispensable to the proper character of a missionary in China. The
relief of bodily suffering (above all, in a country where the medical
art is so low as it is in China) softens the feelings of our nature, and
paves the way for kinder influences over the mind itself. It will open
the family mansion of the most secluded and prejudiced Chinese,
when words or doctrines first propounded would meet an unwilling
or perhaps a hostile listener. Religious teaching and the practice of
the healing art, the comfort of the suffering mind, and the solace of
the tortured body, must go hand in hand in effecting the good work
of "opening" China.
Why is it that the Americans have taken precedence of the English in
this great and glorious work, since the commencement of the war in
particular? For many years, a talented medical missionary, Dr. Parker,
has dispensed his double blessing upon the Chinese at Canton, and
can testify the gratitude of the people, from the highest to the
lowest, and the readiness with which they have accepted his counsel
and his teaching in both capacities. At Macao, Hong-Kong, Kolingsoo,
and Chusan, the Americans have alike preceded us.
There is, however, one great and fatal error to be avoided; and that
is, the rivalry of religious sects among each other, and the attempt to
gain followers at the expense of each other's tenets. It was this want
of unanimity which in some measure produced the decline of the
influence of Roman-catholic missionaries in China.
The garrison which was left by Sir Hugh Gough upon the island of
Kolingsoo consisted of three companies of the 26th regiment, with a
wing of the 18th, and a small detachment of artillery, comprising
altogether about five hundred and fifty men; the whole under the
command of Major Johnstone, of the 26th; and the Druid, with the
Pylades and Algerine, were also to remain there, under the
command of Captain Smith, C.B., as a further support, to ensure the
complete command of the harbour of Amoy.
The number of troops employed during the operations against Amoy
was as follows:—
Officers. Men.
Artillery, European and Native, Captain Knowles 9 240
18th Regiment Royal Irish, Lieutenant Colonel Adams 30 648
26th Regiment (Cameronians), Major Johnstone 8 153
49th Regiment, Lieutenant-Colonel Morris 24 460
55th Regiment, Lieutenant-Colonel Craigie 26 731
Madras Sappers and Miners 6 184
————
Total 103 2416
Four native officers, and serjeants and drummers, are included in the second column.[56]
In the afternoon of the 4th of September, the weather having become calm and fine, the
preconcerted signal for the embarkation of the troops from the town and island of Amoy was made
on board the flag-ship. Upon this sudden order, the troops were paraded in perfect regularity,
without a single instance of drunkenness or misconduct, after eight days of harassing duty on shore,
amid temptations of every kind. Under the direction of Commander Giffard, of the Cruiser, the whole
force was embarked without any accident, by half-past six o'clock, on board the Nemesis and other
steamers, which conveyed them out to their respective transports, in readiness to sail on the
following day. Not even a camp-follower was left behind (and they are generally a very troublesome
class); but, in order to make sure that there was no straggler, the Nemesis was afterwards sent in
again to the town to bring off any one that might accidentally have been left. But the only straggler
which was found, happened to be a fine fat bullock, which was soon put on board the Nemesis and
carried off.
Every preparation was now completed for the departure of our forces on the following morning, the
5th of September.
FOOTNOTE:
[56] List of H.M. ships and vessels, and of the Honourable Company's steam-vessels, in action at
Amoy, 26th of August, 1841.
Wellesley (flag) 72 Captain T. Maitland.
Blenheim 72 Captain T. Herbert.
Blonde 44 Captain T. Bourchier.
Druid 44 Captain H. Smith.
Modeste 18 Captain H. Eyres.
Cruiser 16 Commander Giffard.
Pylades 18 Commander Anson.
Columbine 16 Commander Clarke.
Bentinck 10 Lieutenant R. Collinson.
Algerine 10 Lieutenant T. Mason.
Sesostris steamer 4 Commander Ormsby, I.N.
Phlegethon steamer 4 Lieutenant M'Cleverty, R.N.
Nemesis steamer 4 Mr. W. H. Hall, R.N.
Queen steamer 4 Mr. W. Warden, R.N.
CHAPTER XXVII.
All those persons who have visited Amoy, either out of curiosity or on matters of business, appear to
agree with each other in regarding it as a place peculiarly adapted for the extension of European
trade. The mercantile spirit and enterprise of its inhabitants, and their anxious desire to trade with
foreigners, when not held back by the arbitrary orders of the mandarins, have been long known and
recorded by several travellers, before there was any prospect whatever of the trade being opened.
Mr. Gutzlaff observed respecting it, in the account of his voyage along the coast—"Its excellent
harbour has made it from time immemorial one of the greatest emporiums of the empire, and one of
the most important markets of Asia. Vessels can sail close up to the houses, load and unload with
the greatest facility, have shelter from all winds, and in entering or leaving the port, experience no
danger of getting ashore. The whole adjacent country being sterile, the inhabitants were forced to
seek some means of subsistence elsewhere. Endowed with an enterprising spirit, and unwearied in
the pursuit of gain, they visited all parts of the Chinese empire, gradually became bold sailors, and
settled as merchants all along the coast. Thus they colonized Formosa, which, from that period to
this, has been their granary, and visited and settled in the Indian archipelago, Cochin China, and
Siam. A population constantly overflowing, demanded constant resources for their subsistence, and
this they found in colonization; and thus they spread themselves all along the coast of China, up to
Mantchou Tartary. As soon as the colonists amass sufficient money, they return home, which they
leave again when all is spent." Elsewhere he says, "Many of these merchants, settled in the northern
parts of China, return annually with their profits. It is not surprising, therefore, that a large amount
of Chinese shipping belongs to Amoy merchants, and that the greater part of the capital employed in
the coasting trade is their property. Hence, even this barren tract is become one of the richest in
China, from the enterprise of its inhabitants. Wherever the people go they are rarely found in a state
of abject poverty; on the contrary, they are often wealthy, and command the trade of whole islands
and provinces, as well by their capital as by their superior enterprise and industry."
The English, who had formerly a factory at Amoy, were compelled to relinquish the trade by the
severe extortions to which they were subject. The Dutch continued it for a longer time, but
neglected it when their influence at Formosa ceased. The natives of Amoy have always shewn
themselves ready to cultivate the friendship of foreigners, wherever they have been, and in their
dealings they have a character for honesty beyond all other Chinese. They are more ambitious of
successful mercantile enterprise than of literary distinction or advancement, which is generally so
dear to a Chinaman.
The shops of Amoy are generally well supplied with the necessaries and luxuries of life, the
merchants are civil, and although the town is neither handsome nor very cleanly, and the population
in some parts of it are densely crowded together, still there are many fine houses, which indicate the
possession of wealth and consequence.
An immense trade is carried on between Amoy and the island of Formosa, to which a great number
of emigrants are even still attracted from the province of Fokien. Before the occupation of Hong-
Kong was thought of, several proposals were made for forming a British settlement upon Formosa,
as being conveniently situated for extending our trade with the inhabitants, not only of the adjacent
district of Fokien, but of the whole coast of China. This suggestion was partly encouraged by the
recollection of the settlement which the Dutch once possessed upon the island; but it seemed to be
forgotten that the Dutch were at length forcibly expelled, and that the population having greatly
increased since that period, it is not likely that we should be suffered to retain possession of any part
of the island without being constantly harassed and provoked to bloodshed; moreover, the privilege
of trading with Amoy does away with all probability of advantage to be derived by direct trade with
Formosa.
Among other proposals, that of a settlement upon the Bonin islands (which are said already to
belong to Great Britain) was suggested, with a view to commercial enterprise with China; and Mr.
Tradescant Lay warmly supported this notion. These islands were taken possession of by Captain
Beechey, of H.M.S. Blossom, in 1827, and they extend from latitude 27°, 44', to 26°, 30' N., being
about five days' sail from the Lew-Chew islands, and three from Japan. In the course of a few years,
it is not improbable that Port St. George, the principal harbour, may be resorted to, with the object
of pushing our trade even into Japan itself. At the present moment, indeed, several Englishmen and
other Europeans are settled there, and are principally concerned in the whale fishery. There are also
a good many natives of the Sandwich Islands at Port St. George. The islands are volcanic, but are
rendered productive with moderate cultivation.
It is worth while here to mention that the Bonin Islands and the Sandwich Islands lie directly in the
line of future intercourse between China and the west coast of America, and that it has been
thought not improbable that a new route to China may some day be opened, by way of California
and the islands above-named.
To return from this digression to the island of Formosa, which has claimed our particular interest
since the massacre of so many of our shipwrecked countrymen by the authorities, shortly before the
termination of the late war. In this horrible tragedy no less than two hundred and eighty-three
human beings were put to death in cold blood, without any other crime than that of helplessness,
and without any other object than that of obtaining rewards by fabricated statements, and honours
by false pretences. Formosa was the last conquest of the present Tartar dynasty, and even since it
has been brought under Chinese dominion, the rebellions and disturbances of its unruly inhabitants
have been a frequent source of alarm to the government. The imperial troops have been frequently
defeated with great slaughter, and peace is said to have been purchased by bribes more frequently
than it has been won by conquest. The aboriginal inhabitants are still numerous in the mountain
districts, and along some parts of the eastern shores, but they, are said to be much oppressed by
the Chinese colonists, and also by the authorities.
When the Tartars first began the conquest of China, great numbers of discontented spirits went over
to Formosa from the neighbouring provinces, and it has been recorded that one hundred thousand
people took refuge there. The island belongs to the province of Fokien, along which it is situated at a
distance varying from seventy to one hundred and twenty miles, the passage between it and the
mainland being called the Formosa Channel. The length of this island is about two hundred and
twenty miles, but the breadth of it is extremely irregular. The Chinese population is at present
supposed to amount to about two millions, and is constantly on the increase, by the accession of an
influx of emigrants from the mainland adjoining. They are attracted thither by the fertility of the soil,
and the great facilities for cultivating sugar and rice, which are there grown to an extent sufficient to
supply a vast quantity of these necessary articles to the inhabitants of the mainland, and to employ
several hundred trading junks in the traffic.
It is worthy of remark, that the Dutch contrived to establish themselves upon the island of Formosa,
and ultimately to form a factory there, before the Tartar conquest, and before it was regularly
colonized by the Chinese. The Japanese also partly contributed, though in small numbers, to colonize
the island. The Dutch had a small garrison at a place called Tanshuy, or Tamsui, at the northern
extremity of the island, and another at Kelung, not very for from it. Their object was to make use of
their settlement as a depôt, or centre of trade, from which their operations could be extended along
the coast of China and Japan. Their influence was, however, of very short continuance, as they were
ultimately completely driven out of the island, after some few struggles, by the famous pirate,
Coxinga, in 1662, about thirty or forty years after they had fairly established themselves on it.
The present capital of the island is built upon the site of the principal Dutch factory of former times,
and is called Ty-wan-foo; it is upon the west coast, some distance down towards its southern end.
The harbour has, however, become almost inaccessible, except to vessels of very light draught of
water, owing to the accumulation of sand, which is thought to frequently change its place. Indeed,
the sea has gradually continued to retire from many parts of the coast, and harbours which were
once frequented are at present inaccessible.
From the time of the expulsion of the Dutch, to the period of our operations upon the coast of
China, little seems to have been known or heard of Formosa; and, owing to the jealousy of the
Chinese, and other causes, no attempt seems to have been made to explore the island. The
colonists are described as being generally very turbulent and given to violence, as it has become a
place of refuge for all the bad characters who can manage to escape from the mainland; but it is
also the home of many respectable and enterprising settlers; although, being removed from the
control of the superior officers of the province, they live with less restraint, and therefore readily
become bold and lawless. For the same reason, the local mandarins are cruel, rapacious, and
ignorant; and their behaviour towards our unfortunate countrymen will suffice to stamp them with
the character of treachery and thorough baseness. But the cultivation and prosperity of the island
have increased in a rapid and remarkable manner; and it is evident that British manufactures will
soon be spread among its numerous population, through their intimate connexion with Amoy.
Besides furnishing immense supplies of rice, Formosa also produces great quantities of sugar,
camphor, and tobacco, which are exported to Amoy. A great part of the camphor is already carried
down to Singapore in the trading junks from Amoy, but probably our own trading vessels will
henceforth procure supplies of it on the spot, in exchange for cotton and other manufactured
articles.
Unruly as the people of Formosa are, the island is, nevertheless, somewhat famous for its schools,
which are said to be in a flourishing condition. Mr. Gutzlaff states, that the rich men of Fokien
frequently send their sons over to obtain literary degrees at Formosa; and the Dutch, at an early
period, took pains to spread Christianity among the inhabitants, who, at that time, were
comparatively few in number. A few books on Christianity were translated by them into the
Formosan language, and they were very successful in making converts. Since they abandoned the
island, however, nearly all traces of their early labours have disappeared.
The close connexion of Formosa with Amoy will probably be the means of reviving amongst the
inhabitants some of the lost spirit of Christianity; for we cannot doubt that, in all parts of China, the
increase of missionary labour will keep pace with the increase of commercial intercourse.
The wreck of the Nerbudda transport, on her way up to join the expedition with camp-followers, in
the month of September, 1841, soon after our forces left Amoy, and the loss of the brig Ann, a
trading vessel, on her way down to Macao, from Chusan, in the month of March following, upon the
shores of Formosa, served to attract unusual attention towards that island, and to put us in
possession of some little information respecting the interior.
The history and ultimate fate of our shipwrecked countrymen is calculated to awaken the most
painful interest. On board the Nerbudda there were altogether two hundred and seventy-four
people; of whom, twenty-nine were Europeans, two natives of Manilla, and two hundred and forty-
three natives of India. The captain and the rest of the Europeans, with the two Manilla men, and
only three Indians, got away in the ship's boats immediately after she struck, and were providentially
picked up some days afterwards by a trading schooner, called the Black Swan, on her way down to
Hong-Kong. The unfortunate Indians, to the number of two hundred and forty, who were left upon
the wreck, after remaining by her for five days, managed to construct rafts, upon which they
attempted to reach the shore. Many of them, however, perished in the surf, and others are supposed
to have been murdered by the Chinese plunderers. The exact number, therefore, who fell into the
hands of the Chinese authorities, and were imprisoned and subjected to the greatest privations,
cannot be ascertained; but they were thought to amount, according to the best information which
could be obtained, to more than a hundred and fifty.
On board the brig Ann there were in all fifty-seven souls; of whom, fourteen were natives of Europe
or America, four Portuguese, five Chinamen, and thirty-four natives of India. Out of all those who
were taken prisoners, belonging to both vessels, only nine ultimately escaped an untimely fate, and
were restored at the end of the war, according to the terms of the treaty.
The following account of what befel the unfortunate sufferers on board the Ann will apply, with little
variation, to those who were wrecked before them, in the Nerbudda. It is extracted and condensed
from a curious journal, kept by one of the sufferers, a fine young man, who was a passenger on
board. It was found concealed in his cell, after his unfortunate fate, and cannot but awaken feelings
of deep commiseration for all his companions in distress.[57] It was written upon common Chinese
paper, with a piece of bamboo, and the account was continued to within five or six days of the time
when the final tragedy is supposed to have taken place. It was written day by day, as the various
little occurrences took place, and some of the observations casually made upon the appearance of
the island will be read with great interest; but I have thought proper to omit the minutiæ and
repetition of abrupt and hasty notes, which would have been tedious and of little benefit.
It will here be proper to mention, that prompt redress and "condign" punishment upon the heads of
those high officers, whose false and pitiless misrepresentations occasioned the final catastrophe, has
since been demanded, in firm and dignified terms, by her Majesty's plenipotentiary; and one of the
conditions insisted on was, "that the property of the high authorities of the island, who were
perfidiously concerned in the affair, should be confiscated, and the amount paid over to the officers
of the British government, to be applied to the relief and support of the families of the innocent men
who suffered."
By the orders of the Emperor, a strict investigation has been made into all the circumstances
connected with the dreadful event; and a report has been sent up to Pekin, by the Viceroy of Fokien,
condemnatory of the misrepresentation and duplicity of the authorities of Formosa.
The whole of the fifty-seven individuals who were on board the Ann quitted the wreck at daylight;
and, having marched along the shore about two miles, they fell in with two junks, lying wind-bound
in a small river or creek. They hoped to be able to put to sea, and stretch across to Amoy; but the
gale continued so violent that it prevented them from getting out of the creek. They were not ill-
treated by the Chinese junkmen, but, as they were without food of any kind, and exposed to a cold,
cutting wind, it was soon evident that they must surrender themselves to the Chinese authorities.
Soldiers soon gathered round them in crowds; and, as they had very little ammunition, any attempt
to defend themselves, which might have caused the death of some of the soldiers, or of the mob,
would certainly have been followed by the massacre of the whole party. In the afternoon, they all
gave themselves up, without having fired a single shot, and without attempting to make any kind of
resistance. They were immediately stripped and marched away, exposed to the most cutting wind
and sleet, without any covering, their feet cut by the sharp shells with which the beach was covered,
and with very little allowance of food. It is not surprising, therefore, that two men soon died from
fatigue and exposure, and several others fell from sheer exhaustion, and were obliged to be carried
along in baskets; others were afterwards carried in sedans, more for sake of security than from any
feeling of compassion for them. It was remarked, that during the whole journey of thirteen or
fourteen days, to the capital of the island, the lascars or Indian sailors shewed a great deal of bad
and selfish behaviour towards each other. Each man of the party had a ticket fastened round his
neck, stating what he was, and whence he was brought; being treated in this respect like public
criminals. For a great length of time their food was only salt fish and greens, with sometimes rice.
They suffered all sorts of abuse and indignities in every town and village through which they passed;
but it is remarked, "that the women (who did not appear to be at all secluded) did not join in this,
although they exhibited the usual curiosity of the sex." They were observed throughout the whole
journey to be very plain, but they had a pretty fashion of dressing their hair, by weaving natural
flowers amongst it.[58]
After the first two or three days, they came to a considerable walled town, where they were placed
for the night in two cells, about eight feet by seven feet, in which twenty-five unfortunate beings
were stowed, with nothing to lie upon, the weather being intensely cold. Three guards were placed
over them. The rest of the party were taken by a different route, but they all ultimately reached the
capital. One large town they came to was enclosed, as were some others, by a high, red brick wall.
It was situated in a large paddy swamp or valley, interspersed here and there with small hamlets,
around which the bamboo plantations were growing in great beauty and luxuriance, and of
extraordinary height, many of them measuring upwards of sixty feet. In some of the smaller towns
and villages, the so-called gates (for they all had them) were constructed of bamboo. The country
appeared well cultivated in many parts, and wheat and sugar-cane were met with; but other parts of
the country were very barren, and covered with large stones, such as are called "boulders," in some
parts of England. Generally, the men were made to wear handcuffs, but they were not of great
strength, for some of the party managed to break them off; and they were then carried along in
chairs, under a strong guard of soldiers, but were occasionally allowed to walk. Wherever they went,
the crowd and annoyance of the hosts of curious gazers, who frequently insulted them, was so great
that it was a relief to get lodged in the common gaol, which was divided into several cells, each cell
having cages in it, made of wooden bars, just like the dens of wild beasts. The cells were also
provided with a regular pair of stocks, in order to afford greater security, if required. One of the cells
was filled with Chinese prisoners.
The great object of the mandarins now appeared to be, to get some of the party to admit that the
Ann was a man-of-war, sent to look after the crew of the Nerbudda, who were known to be still upon
the island. With this view, two of the men were mercilessly beaten, but without the desired effect.
So common and so public a practice did opium-smoking appear to be, that even the soldiers who
acted as an escort carried their opium-pipes in their girdles. For the first twelve days, the prisoners
were never allowed to wash even their faces, and at length they could only do it in a dirty pool by
the road side. For the last four days before they reached the capital, called Ty-wan-foo, they were
compelled to wear leg-irons as well as handcuffs. Generally, they were allowed to purchase their own
food during the journey; for which purpose a little money was given to them, at the rate of one
mace, or about fivepence, a day. But this was only after the first few days.
It was remarked that wheel-carts were in common use in the island, and tracks of them were seen
in all directions. On the mainland of China these are unknown, except in the neighbourhood of
Pekin; but, in the island of Hainan, to the southward of Canton, they are very common, and similar
in construction to those in use upon Formosa. They are, however, very clumsy and inconvenient; the
wheels, which are small, being composed of two semicircular pieces of solid wood, joined together,
with the axle fixed into the wheel itself, so as to revolve with it, and not within it, but made to turn
round under the body of the cart. The roads or causeways are generally broader than upon the
mainland, and were in many places shaded with bamboos on each side. Several rivers were crossed
near the capital, and the country was somewhat improved in appearance.
About twenty miles from Ty-wan-foo they passed a night in a large town, with walls built of chunam;
at the entrance of which were placed several very long guns, not mounted on carriages, but fixed
upon the ground, rather to indicate their good intentions than their ability to perform them. Here
again they were lodged in the common gaol; and, on the following morning, the Chinese servant
who had been taken prisoner with them had a chain put round his neck, in addition to his leg-irons
and handcuffs. The next night (the last before they entered the capital) was spent at an inn by the
road-side, which was so crowded with travellers that scarcely any food could be procured. The
Chinese had regular fights and scrambles for the little which was to be had, and their appetites
appeared by no means delicate; but, whether their hunger was appeased or not, they were all
prepared in the evening to enjoy in good earnest the luxury of the opium-pipe, soldiers and
travellers all alike; nor did the two mandarins who were present interfere in any manner to point out
its impropriety.
On the 24th March, (fourteenth day since the wreck,) they were destined to make their wretched
entrance into the capital. At the distance of six or seven miles from it, they were met by an officer
and a few soldiers, by whom their names and their numbers were called over, according to a list
which the officer held in his hand, and they were then separated into smaller parties, and led by
different routes into the city. As they approached the gate, they, for the first time, caught a glimpse
of the sea, with a few junks at anchor at a distance, towards which they hopelessly strained their
longing eyes. The walls of the city appeared to be in a state of dilapidation, except near the
gateway, where they had been recently repaired and whitewashed. The prisoners were now fairly
within the capital of Formosa, and were conducted to an open space, planted thickly with trees, but
broken up by rough watercourses, over which there were several bridges of stone. Thence they were
led through back lanes, avoiding the principal streets, to the house of a high mandarin, in front of
which they halted for a short time; and such was the pressure of the crowd and the curiosity of the
people, that the chairs in which they had been brought were nearly pulled to pieces before they
were ordered to get out and enter the outer gateway of the mandarin's house.
Here they were drawn up in line, to have the tickets round their necks copied; but before the
process could be half finished, the pressure of the crowd became so great that the mandarins were
obliged to discontinue the task. A ludicrous scene followed, which, for the moment, afforded
amusement even to the prisoners themselves. The enraged mandarins charged the mob in great
fury, and whipped them with their long tails, which, having silk woven on to the ends, gave some
tolerable cuts to the people's faces. For a few minutes our hapless prisoners were put for refuge into
a small temple which was close at hand; but even here the mob pressed so hard upon them that the
door was nearly smashed in; and, as a last resource, they were marched off, with heavy irons on
their legs, which bruised them at every step, to a prison in the courtyard of a superior mandarin's
house, about one hundred yards distant. Here their treatment was very bad; for several successive
days they were brought up before the mandarin to answer an infinity of questions, many of them
very puerile, about the names, ages, and duties of every one on board the Ann; also about
geography and the possessions of Great Britain, and where the poppy was grown; how money was
raised, &c. &c. The Chinese carpenter of the vessel acted as interpreter; and, on one occasion, both
he and the other Chinaman were severely flogged with bamboos.
After some time, those who could draw were allowed to sketch ships, carriages, and other things,
which exceedingly amused the Chinese, who were glad to purchase them; so that by these means
they were able to procure food and tobacco, and thus to diminish in some degree their chances of
being carried off by starvation or sickness.
After the lapse of a week or two, fever broke out, and they were then separated into smaller parties,
and put into different cells or prisons, some faring better, some worse, according to the temper or
caprice, or even roguery, of the particular jailer who chanced to have charge of them. One of these
wretches seems to have been a perfect fiend of his class; he kept one party of ten miserable human
beings in a den so small that not one of them could lie down at night. It will scarcely be believed
that they were made to exist for two whole months in this horrid black hole, only eleven feet six
inches long, by seven feet six inches wide; grudging each other every little inch of room, and longing
even for the little bit of space which the single insensible bucket, which was the only piece of
furniture, occupied in their den. Here were ten human beings stowed away together, some sick,
some sore, and all in pain and misery. For some time they were not permitted to come out of the
den at all, but at last they were let out once a day, and were allowed a very little water to wash
themselves; only two or three, however, could wash themselves on the same day, so that the whole
of them could only be able to wash themselves once in three days. Of course, they were dreadfully
infected with vermin of every kind, and, as the author of the journal expresses it, "A few weeks have
sufficed to bring me down from a strong hale man, to a wretched helpless being, disgusted with
myself."
Many attempts were made to get a note sent across to Amoy, to give information of their situation;
and the promise of one hundred dollars on its safe delivery, and one hundred more on bringing an
answer back, (to be paid at Amoy,) sufficed to induce a tolerable trusty Chinaman to undertake the
task. We shall see presently how far it succeeded. It has before been stated that the several parties
fared differently, according to the humanity or rapacity of the particular jailer. Something also
depended upon the particular mandarin under whose supervision they were placed, but it is noticed
that the highest, or red-button mandarin, was the best of all, and frequently ordered some of the
hardships they complained of to be remedied, particularly as regarded the quality of the food.
On the other hand, it is stated, that one of the jailers, who was humane enough to allow his party of
prisoners to be shaved, was taken before a mandarin and punished with fifty strokes of the bamboo;
after which, no visitors were allowed to see them at all, and the jailer became very sulky, except
when he was drunk, which he generally was, by the use of opium, every evening. Sometimes they
were taken out of prison in order to draw for the mandarins, at others, to undergo repeated
examinations for their amusement. In the first instance, however, the object invariably was, to
betray them into an admission, however remote, that the vessel was really a man-of-war. But it was
quite evident that they knew perfectly well that she was not so, and at length the red-button
mandarin put an end to this part of the business. From this time, their questions were more of a
general nature, but many of them were exceedingly absurd. The mention of Sir Henry Pottinger's
name (for they appeared already to have heard of him) invariably made them angry, and on one
occasion they inquired whether he was a white or a black man. They also inquired a good deal about
the Queen, her court, and ministers, mode of life, &c., and how many husbands she was allowed to
have; expressing great astonishment when they learned that in Europe kings and queens, as well as
private individuals, had only one wife or husband; and then they proceeded to enumerate the virtues
of their own emperor, and to plume themselves upon their own cleverness.
On one occasion, they asked whether America had not, some time or other, been situated in
England? whether a man could now walk from London to America in a week? how large London was,
and how many outside (foreign) nations are subject or tributary to England? Endless were their
curious questions, and on one occasion they exhibited an officer's jacket, and a corporal's coat with
the 55th button on it, and particularly inquired the use of an epaulette, which they held up, fancying
it was intended to be worn on the head.
During the first half of the month of May, it rained incessantly, and they were very imperfectly
protected from its effects. In fact, the rain always beat through their roof, and when it was heavy, or
long continued, it flooded their den: the least bit of dry plank, or a partially sheltered corner, was
matter of envy and contention; and, as may be supposed, they not only suffered from bad food,
confinement, vermin, and ill-health, but were incessantly tormented with the most venomous
mosquitoes, producing inflammation and sores. In this condition they were kept in the most
harassing state of suspense; one day being assured that they would be sent away in a month;
another, that they had no chance of liberty for six months; and the very next, perhaps, that their
heads would soon be taken off.
Fortunately, the talent for drawing possessed by Mr. Gully and Captain Denham, served to gain for
them friends and pacify enemies.
In this way, month after month continued to drag its slow length along. At the end of about three
months' close confinement, a slight change for the better took place; they were moved into rather
better quarters, where they were only three together, so that they had more room to breathe; they
were also allowed water to wash themselves, and a little money was given to them. It was thought
that this arose in consequence of information received by the authorities that there was some
chance of an attack being made upon this island, by our forces at Amoy, with a view to liberate the
prisoners. It was now ascertained, also, that the fisherman who had promised to carry over the
letter to Amoy, two months before, had succeeded in his attempt, and an answer had been brought
back by him, which held out the prospect of speedy release. Another letter was also sent off to
Amoy; so that now at length their hopes again revived. But sickness had already begun its work, and
their minds were so depressed that even the boldest, who tried to bear up bravely to the last,
recorded his feelings that "One miserable day passed after another, with nothing to help them to
break in upon the wretchedness of their existence; no exercise being permitted, and nothing, in fact,
to relieve the dreadful monotony of such prison life." And what was the little improvement in their
lot, which resulted from their removal into other cells? "We now, (three of us,") said he, "have five
planks with a mat upon them to sleep on, and glad we are to get into this new place, which is the
Executioners Den, and which, until we had ourselves cleaned it, could never have been cleaned since
it was built." On other occasions it is noted, "we scalded our clothes this morning, to kill the vermin."
It was thought that the day they were removed into this new berth must have been the Emperor's
birthday, or some day of rejoicing, for they had at the same time a dinner of roast pork, with sweet
cakes, and each man received one mace, or fivepence in money. But this was too good to last—a
mere freak of fortune! Generally speaking, their food was so bad, that a great part of it was thrown
away, and it was only by quarrelling with the jailers, and threatening to complain to the high
mandarin, that they could succeed in procuring any eatable food at all.
In the month of June, several shocks of an earthquake were felt, followed by terrific storms of
thunder and lightning. It is due to the better class of mandarins to remark, that when complaints
were made to them, they procured some temporary improvement for the prisoners.
On the 4th of July, it was made known that honours and rewards had been largely conferred upon
the mandarins, for having contrived to make so many prisoners. This was in answer to their false
accounts of the business to the Emperor, in which they said that they had attacked and destroyed
two English men-of-war which came prying into the coast, and had taken all the people prisoners,
enumerating the number of black, and red, and white barbarians, and the quantity of barbarian
guns.
On the 10th of July, Mr. Gully, who had necessarily been ailing for some time, became seriously ill
with dysentery, brought on in a great measure by eating large quantities of mangoes. The Chinese
recommended him two cures for it; one was, to eat the skins of the mangoes alone; the other, to eat
opium. The former he found to have a good effect, at least so far that his complaint improved under
the treatment; the latter he was able to purchase at a moderate price from the visitors, who brought
it on purpose for him; it was different from the extract which is used for smoking, and apparently
much less powerful.
The same mandarin who had given them a treat upon the Emperor's birthday all along shewed more
interest in their condition than any of the others; and one day, in the hope of inducing him to give
them some kind of indulgence, they told him that it was the birthday of the Queen of England's
eldest child, and that they all entertained so strong a feeling of "filial obedience" and affection
towards their queen, that they wished to celebrate the event. To their great surprise and delight, the
mandarin's heart was moved by this appeal, and he gave each of them money; to some five mace,
to others three, (equal to about two shillings,) and then sent them a good dinner, and made himself
quite agreeable; and, of course, all the inferior officers, including the jailers, took their tone for the
day from their superior. On another occasion, the lascars were all brought up before the chief
mandarin, having had new clothes first given to them, and he himself then presented each of them
with a fan!
All these circumstances naturally tended to revive their hopes, and little did they dream of the
horrible catastrophe which was soon to take place. Towards the end of July they were informed, that
in the course of half a moon more an answer would be received from Pekin, containing the
Emperor's commands as to what was to be done with the prisoners; and they were warned that, if
his majesty ordered that they should be decapitated, it would immediately be carried into effect.
From this it would seem that the authorities fully anticipated that the representations which they had
made would induce the Emperor to issue such a cruel command; but the prisoners themselves still
retained sufficient hope to induce them to disbelieve the probability of such a tragedy. With the
exception of Captain Denham (whose life was saved) and the Chinese carpenter, it does not appear
that any of them were tortured; but the dreadful cries of some of the Chinese prisoners could be
distinctly heard; and two poor fellows were seen passing by with their hands blackened, having been
condemned to have them chopped off.
One remark is worth recording—namely, that the mandarins, from the highest to the lowest, as well
as all their servants and attendants, were in the constant habit of smoking opium. Tobacco was also
in general use, as elsewhere in China, and was extensively cultivated on the island. There was also
noticed (what should have been mentioned before) a curious vine-like plant, grown upon trellis-
work, and frequently observed to be carefully covered up with mats; what it was no one knew, but
more care and attention seemed to be bestowed upon it than upon anything else which was seen
upon the island.
The final tragedy is believed to have taken place upon the 12th or 13th of August, and is too horrible
to dwell upon. They were beheaded with the sword.
It is difficult to account for their having reserved nine individuals from the general massacre. Of
these, six were Europeans or Americans, and three natives of India. It is supposed that they were
retained in order to be sent to Pekin, to be there cut in pieces. Fortunately, the treaty of peace saved
their lives, and they were at length conveyed to Amoy, and there met with all the attention they so
much needed from their own countrymen.
FOOTNOTES:
[57] The information in the text was extracted from the manuscript, more than a year ago, in
China. But the journals of Mr. Gully and Captain Denham have been recently published in full, in
this country.
[58] Probably the women at Formosa are much less numerous, compared with the men, than in
most other places. The men come over from the mainland, but do not bring their women. It is
believed that infanticide of female children is very prevalent at Amoy. The men are driven by
poverty to emigrate, and have no means of providing for female children, who are therefore
frequently smothered or drowned.
CHAPTER XXVIII.
On leaving the bay of Amoy, on the 5th of September, the appointed places for the rendezvous of
the fleet of men-of-war and transports, in case of separation, were successively the so-called
Buffalo's Nose, at the entrance of the Chusan group; Keeto Point, a promontory running out from the
mainland towards Chusan; and, lastly, the bay or harbour of Tinghai, the capital of Chusan. The
progress of the squadron was slow for some days, owing to light winds and a heavy swell; and the
Nemesis, being very light in the water, and having, moreover, a leak in her bottom, (after the
accident at Amoy,) was kept pretty close in shore, to avoid the swell outside, but seldom entirely lost
sight of the fleet. A considerable quantity of floating wood was picked up alongshore, which was
very acceptable for fuel, of which she had only a very small supply remaining on board.
On the 13th, eight days after leaving Amoy, the north-east monsoon set in rather suddenly, and
somewhat earlier than usual, with heavy squalls and a thick fog, which caused the unavoidable
separation of the squadron. At the commencement of this change of weather, the Nemesis lost her
fore-top-mast and top-gallant-mast, but continued her course leisurely alongshore until the following
day, when she came to anchor under a small island at the mouth of the river Taitchou, about thirty-
five miles from Sheipoo, and between fifty and sixty from the Buffalo's Nose.
On the 16th, Capt. Hall landed upon the island above mentioned, under which he had taken shelter,
with a party of men, to look for wood, which was much needed for fuel, and also for refreshments
for the crew, and then took the opportunity of ascending a high hill, to take a survey of the
neighbouring country. The haze cleared off sufficiently to enable him to discover the entrance to an
extensive harbour, which proved to be that of Sheipoo, where there is a considerable trading town.
He thought that he could also make out something like the appearance of batteries or field-works at
the entrance.
The Nemesis now stood in for the entrance of the harbour, which was very narrow, but fortunately,
she soon fell in with a fishing-boat, in which were several fishermen busy about their nets, one of
whom was made to come on board and pilot the vessel into the harbour; and he was promised ten
dollars for his services if he took her in without any accident; but, if she touched ground, he was
threatened to be immediately run up to the yard-arm. The poor fellow had never even seen a
steamer or devil-ship before, and was not a little alarmed. But he perfectly understood the
conditions, and gradually recovered his self-possession.
The tide swept so rapidly into the narrow entrance of the harbour, that the Nemesis was fairly
carried through the passage before the two small field-works, which were intended to protect it,
could bring a single gun to bear upon the vessel; but the Chinese were seen running down from
their little encampment above, to man the guns.
At the bottom of the harbour or basin, the town now came into full view, with a large number of
trading-junks of every kind, moored in lines close to each other on one side of the town; while on
the other, or the left, as you looked towards it, there was a small fort, which appeared to have been
recently repaired and strengthened, but, like most other Chinese forts, was left almost unprotected
in the rear.
Upon a rising ground behind the fort, a small body of troops, about five or six hundred in number,
were drawn up, so that the Chinese were evidently prepared for defence. The Nemesis immediately
ran in towards the fort, and took up a flanking position, anchoring by the stern between it and the
town, so as to bring her guns to bear with the greatest advantage, without exposing herself to the
direct fire of the fort. Shot, shell, and canister, were now poured in, and the fort was soon silenced.
But the troops could now be seen descending from the hill behind, and bringing heavy ginjals with
them, mounted on triangular stands, as if they intended to oppose a landing. However, a few
discharges of grape-shot threw them into great disorder, killing many of them; Capt. Hall then
landed, at the head of all the men who could be spared from the ship, accompanied by Mr. Gully,
and took possession of the fort, the Chinese flying before them; four guns, two brass and two iron
ones, were destroyed in the fort, the temporary sheds and buildings were set on fire, and water was
poured into the magazine to destroy the powder.
The whole party having now returned on board, boats were sent out, manned and armed, to search
for fuel, and also to attempt to capture three large war-junks, which had been seen on the way up
the harbour. All the trading-junks were left unmolested; but wood for fuel was so much needed on
board, that several of the wood-junks were soon picked out, well filled with the necessary article.
The opportunity was extremely fortunate, and in a short time, no less than seven boat-loads of
excellent wood were obtained, amounting in all to about seventy tons. Much labour was required to
bring off so large a quantity, and to stow it away expeditiously; nevertheless, during this operation,
one of the war-junks was captured, (the crew having deserted her,) and, as soon as she was towed
clear of the town and shipping, so as not to cause any unnecessary damage, she was set on fire in
the middle of the harbour, and shortly blew up. Two guns, together with a quantity of ginjals,
matchlocks, swords, &c., were destroyed in her.
But the day's work was not finished yet. About two o'clock the cutters were sent away, manned and
armed, under Mr. Galbraith, to destroy the other two war-junks which had been seen in the morning.
One of them blew up close in shore, but the other was towed out into the middle of the harbour,
before she was set on fire. One was found to mount fourteen guns, and contained a large quantity
of powder, with numerous warlike implements of various kinds.
The whole of this day's work was exceedingly interesting. The hills which surrounded the harbour
were covered with people, who crowded out of the town, and from all the neighbouring villages, to
witness the exploits of the "devil-ship," the rapidity of whose movements, the precision of her fire,
and the volumes of smoke and steam which issued from her, seemed to awaken feelings of awe and
mute astonishment, even more than fear. There they stood for hours, apparently unconcerned
spectators of passing events; and as they saw the destruction of the war-junks, while the merchant-
junks remained uninjured, they appeared satisfied that no mischief was threatened against the
unarmed inhabitants so long as they did not interfere. The neighbourhood of the town along the
shore was laid out in very neatly cultivated gardens, and everything bore indications of a thriving
and well-ordered community.
The day was now far advanced, and it only remained to capture the two forts or field-works upon
the island, just within the mouth of the harbour. A shot or two had previously been fired at them in
the course of the morning, but it was now determined to take possession of them, and destroy the
works. On nearing them, a few shells and rockets were discharged into them, and the boats then put
off, manned and armed, under Capt. Hall. The Chinese had only just abandoned them. The two
field-works were very near each other, and were found to mount nine guns, which were spiked, their
carriages destroyed, and the tents of the soldiers were set on fire.
The poor Chinese fisherman who had acted as pilot was of course liberated as soon as the harbour
was cleared, and he appeared no less astonished than overjoyed when the promised ten dollars
were counted out into his hands.
On the following day, the 18th, the Nemesis reached the appointed rendezvous at Buffalo's Nose,
and found the Sesostris was the only vessel which had preceded her, the rest of the fleet having
been kept back by contrary winds and hazy weather. When we remember what a large number of
hired transports and store-ships passed up and down along the coast of China from this time to the
close of the war, many of which had frequently a great part of their crew sick, we cannot but be
surprised[59] that so few accidents happened. The inaccuracy of the surveys of the coast which had
been then made; the wrong position on the charts of most of the numerous islands which stand out
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com
Ad

Recommended

iOS 9 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 2nd Ed...
iOS 9 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 2nd Ed...
jussiefathey
 
iOS 9 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 2nd Ed...
iOS 9 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 2nd Ed...
exzanyangdi
 
iOS 9 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 2nd Ed...
iOS 9 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 2nd Ed...
mycielyonne
 
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
assangkaoua
 
Programming iOS 5 2nd Edition Matt Neuburg
Programming iOS 5 2nd Edition Matt Neuburg
saertahai
 
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
jungieaugi
 
Programming Ios 5 2nd Edition 2nd Early Release Draft Matt Neuburg
Programming Ios 5 2nd Edition 2nd Early Release Draft Matt Neuburg
lindzpeccoo
 
C 7 0 in a Nutshell The Definitive Reference 7th Edition Joseph Albahari
C 7 0 in a Nutshell The Definitive Reference 7th Edition Joseph Albahari
becelaeeppo
 
C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
nkokiveloce
 
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
maneskortyjt
 
Cocoa and Objective C Up and Running Foundations of Mac iPhone and iPod touch...
Cocoa and Objective C Up and Running Foundations of Mac iPhone and iPod touch...
quizaloan
 
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
matbarnargis59
 
Programming Interactivity 2nd Edition 2nd Edition Joshua Noble
Programming Interactivity 2nd Edition 2nd Edition Joshua Noble
maanggeido20
 
Refactoring JavaScript turning bad code into good code First Edition Burchard
Refactoring JavaScript turning bad code into good code First Edition Burchard
simbajdzikie4
 
Ruby Best Practices Increase Your Productivity Write Better Code 1st Edition ...
Ruby Best Practices Increase Your Productivity Write Better Code 1st Edition ...
forbahchonev
 
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
nieysaiotti
 
Learning Android 1st Edition Marko Gargenta
Learning Android 1st Edition Marko Gargenta
desiovissio
 
Java Network Programming Fourth Edition Harold Elliotte
Java Network Programming Fourth Edition Harold Elliotte
zubinrlondoit
 
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
batyegrocez1
 
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
thoramenzab0
 
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
pundaiarleny
 
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
lalikaukpono
 
Java Network Programming Fourth Edition Elliotte Rusty Harold
Java Network Programming Fourth Edition Elliotte Rusty Harold
nakorocorway
 
Programming TypeScript Making your JavaScript applications scale Boris Cherny
Programming TypeScript Making your JavaScript applications scale Boris Cherny
kholiheijne
 
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
reknesluima
 
Istio Up Running Using a Service Mesh to Connect Secure Control and Observe 1...
Istio Up Running Using a Service Mesh to Connect Secure Control and Observe 1...
kecketatyz
 
LearningPython.pdf
LearningPython.pdf
Shenthilkumar Subburam
 
Learning Web App Development 1st Edition Semmy Purewal
Learning Web App Development 1st Edition Semmy Purewal
molaxmeizu
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 

More Related Content

Similar to Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th Edition Matt Neuburg (20)

C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
nkokiveloce
 
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
maneskortyjt
 
Cocoa and Objective C Up and Running Foundations of Mac iPhone and iPod touch...
Cocoa and Objective C Up and Running Foundations of Mac iPhone and iPod touch...
quizaloan
 
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
matbarnargis59
 
Programming Interactivity 2nd Edition 2nd Edition Joshua Noble
Programming Interactivity 2nd Edition 2nd Edition Joshua Noble
maanggeido20
 
Refactoring JavaScript turning bad code into good code First Edition Burchard
Refactoring JavaScript turning bad code into good code First Edition Burchard
simbajdzikie4
 
Ruby Best Practices Increase Your Productivity Write Better Code 1st Edition ...
Ruby Best Practices Increase Your Productivity Write Better Code 1st Edition ...
forbahchonev
 
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
nieysaiotti
 
Learning Android 1st Edition Marko Gargenta
Learning Android 1st Edition Marko Gargenta
desiovissio
 
Java Network Programming Fourth Edition Harold Elliotte
Java Network Programming Fourth Edition Harold Elliotte
zubinrlondoit
 
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
batyegrocez1
 
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
thoramenzab0
 
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
pundaiarleny
 
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
lalikaukpono
 
Java Network Programming Fourth Edition Elliotte Rusty Harold
Java Network Programming Fourth Edition Elliotte Rusty Harold
nakorocorway
 
Programming TypeScript Making your JavaScript applications scale Boris Cherny
Programming TypeScript Making your JavaScript applications scale Boris Cherny
kholiheijne
 
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
reknesluima
 
Istio Up Running Using a Service Mesh to Connect Secure Control and Observe 1...
Istio Up Running Using a Service Mesh to Connect Secure Control and Observe 1...
kecketatyz
 
LearningPython.pdf
LearningPython.pdf
Shenthilkumar Subburam
 
Learning Web App Development 1st Edition Semmy Purewal
Learning Web App Development 1st Edition Semmy Purewal
molaxmeizu
 
C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
C 40 In A Nutshell Fourth Edition Joseph Albahari Ben Albahari
nkokiveloce
 
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
maneskortyjt
 
Cocoa and Objective C Up and Running Foundations of Mac iPhone and iPod touch...
Cocoa and Objective C Up and Running Foundations of Mac iPhone and iPod touch...
quizaloan
 
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
matbarnargis59
 
Programming Interactivity 2nd Edition 2nd Edition Joshua Noble
Programming Interactivity 2nd Edition 2nd Edition Joshua Noble
maanggeido20
 
Refactoring JavaScript turning bad code into good code First Edition Burchard
Refactoring JavaScript turning bad code into good code First Edition Burchard
simbajdzikie4
 
Ruby Best Practices Increase Your Productivity Write Better Code 1st Edition ...
Ruby Best Practices Increase Your Productivity Write Better Code 1st Edition ...
forbahchonev
 
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
nieysaiotti
 
Learning Android 1st Edition Marko Gargenta
Learning Android 1st Edition Marko Gargenta
desiovissio
 
Java Network Programming Fourth Edition Harold Elliotte
Java Network Programming Fourth Edition Harold Elliotte
zubinrlondoit
 
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
batyegrocez1
 
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
thoramenzab0
 
Learning Swift 3 Early release 3rd Edition Jonathan Manning
Learning Swift 3 Early release 3rd Edition Jonathan Manning
pundaiarleny
 
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning 2024 scribd...
lalikaukpono
 
Java Network Programming Fourth Edition Elliotte Rusty Harold
Java Network Programming Fourth Edition Elliotte Rusty Harold
nakorocorway
 
Programming TypeScript Making your JavaScript applications scale Boris Cherny
Programming TypeScript Making your JavaScript applications scale Boris Cherny
kholiheijne
 
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
reknesluima
 
Istio Up Running Using a Service Mesh to Connect Secure Control and Observe 1...
Istio Up Running Using a Service Mesh to Connect Secure Control and Observe 1...
kecketatyz
 
Learning Web App Development 1st Edition Semmy Purewal
Learning Web App Development 1st Edition Semmy Purewal
molaxmeizu
 

Recently uploaded (20)

How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDM & Mia eStudios
 
Community Health Nursing Approaches, Concepts, Roles & Responsibilities – Uni...
Community Health Nursing Approaches, Concepts, Roles & Responsibilities – Uni...
RAKESH SAJJAN
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
“THE BEST CLASS IN SCHOOL”. _
“THE BEST CLASS IN SCHOOL”. _
Colégio Santa Teresinha
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDMMIA Practitioner Student Reiki Yoga S2 Video PDF Without Yogi Goddess
LDM & Mia eStudios
 
Community Health Nursing Approaches, Concepts, Roles & Responsibilities – Uni...
Community Health Nursing Approaches, Concepts, Roles & Responsibilities – Uni...
RAKESH SAJJAN
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Ad

Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th Edition Matt Neuburg

  • 1. Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics 5th Edition Matt Neuburg download https://ebookbell.com/product/ios-12-programming-fundamentals- with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt- neuburg-22034678 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics Matt Neuburg https://ebookbell.com/product/ios-12-programming-fundamentals-with- swift-swift-xcode-and-cocoa-basics-matt-neuburg-153701528 Ios 12 Programming Fundamentals With Swift Matt Neuburg https://ebookbell.com/product/ios-12-programming-fundamentals-with- swift-matt-neuburg-170540748 Ios 12 Programming For Beginners An Introductory Guide To Ios App Development With Swift 42 And Xcode 10 Third Edition Clayton https://ebookbell.com/product/ios-12-programming-for-beginners-an- introductory-guide-to-ios-app-development-with-swift-42-and- xcode-10-third-edition-clayton-11793154 Mastering Ios 12 Programming Third Edition Donny Wals https://ebookbell.com/product/mastering-ios-12-programming-third- edition-donny-wals-61024906
  • 3. Programming Ios 12 Dive Deep Into Views View Controllers And Frameworks Matt Neuburg https://ebookbell.com/product/programming-ios-12-dive-deep-into-views- view-controllers-and-frameworks-matt-neuburg-22124124 Programming Ios 12 Matt Neuburg https://ebookbell.com/product/programming-ios-12-matt- neuburg-170810434 Ios Programming For Beginners Learn Ios 15 Swift 53 And Swiftui And Xcode 123 Step By Step Very Easy Rizk https://ebookbell.com/product/ios-programming-for-beginners-learn- ios-15-swift-53-and-swiftui-and-xcode-123-step-by-step-very-easy- rizk-37232402 Ios Programming For Beginners Learn Ios 15 Swift 53 And Swiftui And Xcode 123 Step By Step Very Easy 1st Edition Rizk https://ebookbell.com/product/ios-programming-for-beginners-learn- ios-15-swift-53-and-swiftui-and-xcode-123-step-by-step-very-easy-1st- edition-rizk-50580692 Ios 14 Programming For Beginners Fifth Edition Get Started With Building Ios Apps With Swift 53 And Xcode 12 5th Edition Ahmad Sahar https://ebookbell.com/product/ios-14-programming-for-beginners-fifth- edition-get-started-with-building-ios-apps-with-swift-53-and- xcode-12-5th-edition-ahmad-sahar-217628142
  • 5. Matt Neuburg iOS 12 Programming Fundamentals with Swift SWIFT, XCODE, AND COCOA BASICS C o v e r s i O S 1 2 , X c o d e 1 0 , a n d S w i f t 4 . 2
  • 7. Matt Neuburg Boston iOS 12 Programming Fundamentals with Swift Swift, Xcode, and Cocoa Basics FIFTH EDITION
  • 8. ISBN: 978-1-492-04455-0 [LSI] iOS 12 Programming Fundamentals with Swift, Fifth Edition by Matt Neuburg Copyright © 2018 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://oreilly.com/safari). For more information, contact our corporate/insti‐ tutional sales department: 800-998-9938 or [email protected]. Editor: Rachel Roumeliotis Production Editor: Kristen Brown Proofreader: O’Reilly Production Services Indexer: Matt Neuburg Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Matt Neuburg April 2015: First Edition October 2015: Second Edition October 2016: Third Edition October 2017: Fourth Edition September 2018: Fifth Edition Revision History for the Fifth Edition 2018-09-26: First release See http://oreilly.com/catalog/errata.csp?isbn=9781492044550 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 12 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.
  • 9. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 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 13 Namespaces 13 Modules 14 Instances 15 Why Instances? 17 The Keyword self 19 Privacy 20 Design 22 Object Types and APIs 23 Instance Creation, Scope, and Lifetime 25 Summary and Conclusion 25 2. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Function Parameters and Return Value 27 Void Return Type and Parameters 31 Function Signature 32 External Parameter Names 32 iii
  • 10. Overloading 34 Default Parameter Values 35 Variadic Parameters 35 Ignored Parameters 36 Modifiable Parameters 37 Function in Function 40 Recursion 42 Function As Value 42 Anonymous Functions 45 Define-and-Call 51 Closures 52 How Closures Improve Code 54 Function Returning Function 55 Closure Setting a Captured Variable 58 Closure Preserving Its Captured Environment 59 Escaping Closures 60 Curried Functions 60 Function References and Selectors 62 Function Reference Scope 64 Selectors 65 3. Variables and Simple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Variable Scope and Lifetime 69 Variable Declaration 71 Computed Initializer 74 Computed Variables 76 Setter Observers 79 Lazy Initialization 80 Built-In Simple Types 82 Bool 82 Numbers 84 String 92 Character and String Index 96 Range 101 Tuple 103 Optional 105 4. Object Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Object Type Declarations and Features 119 Initializers 121 Properties 127 Methods 130 iv | Table of Contents
  • 11. Subscripts 132 Nested Object Types 135 Instance References 135 Enums 137 Raw Values 138 Associated Values 140 Enum Case Iteration 142 Enum Initializers 143 Enum Properties 144 Enum Methods 145 Why Enums? 146 Structs 147 Struct Initializers, Properties, and Methods 147 Struct As Namespace 149 Classes 149 Value Types and Reference Types 150 Subclass and Superclass 156 Class Initializers 161 Class Deinitializer 169 Class Properties and Methods 170 Polymorphism 172 Casting 175 Casting Down 176 Type Testing and Casting Down Safely 176 Type Testing and Casting Optionals 178 Bridging to Objective-C 178 Type References 180 From Instance to Type 180 Type as Value 181 The Keyword Self 183 Comparing Types 184 Summary of Type Terminology 185 Protocols 186 Why Protocols? 187 Protocol Type Testing and Casting 189 Declaring a Protocol 190 Protocol Composition 191 Optional Protocol Members 192 Class Protocol 194 Implicitly Required Initializers 195 Literal Convertibles 196 Generics 197 Table of Contents | v
  • 12. Generic Declarations 200 Contradictory Resolution 202 Type Constraints 203 Explicit Specialization 205 Generic Invariance 207 Associated Type Chains 208 Where Clauses 210 Extensions 213 Extending Object Types 213 Extending Protocols 215 Extending Generics 217 Umbrella Types 219 Any 219 AnyObject 221 AnyClass 223 Collection Types 224 Array 224 Dictionary 240 Set 247 5. Flow Control and More. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Flow Control 253 Branching 254 Loops 266 Jumping 271 Privacy 286 Private and Fileprivate 288 Public and Open 289 Privacy Rules 290 Introspection 290 Operators 291 Synthesized Protocol Implementations 295 Key Paths 298 Dynamic Member Lookup 300 Memory Management 301 Memory Management of Reference Types 301 Exclusive Access to Value Types 308 Part II. IDE vi | Table of Contents
  • 13. 6. Anatomy of an Xcode Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 New Project 313 The Project Window 315 The Navigator Pane 317 The Utilities Pane 322 The Editor 323 The Project File and Its Dependents 325 What’s In the Project Folder 326 Groups 327 The Target 328 Build Phases 328 Build Settings 330 Configurations 331 Schemes and Destinations 333 From Project to Built App 335 Build Settings 338 Property List Settings 338 Nib Files 339 Additional Resources 340 Code Files 342 Frameworks and SDKs 343 The App Launch Process 345 The Entry Point 345 UIApplicationMain 346 App Without a Storyboard 348 Renaming Parts of a Project 349 7. Nib Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 The Nib Editor Interface 352 Document Outline 353 Canvas 356 Inspectors and Libraries 358 Nib Loading 359 When Nibs Are Loaded 360 Manual Nib Loading 361 Connections 363 Outlets 363 The Nib Owner 364 Automatically Configured Nibs 368 Misconfigured Outlets 369 Deleting an Outlet 371 More Ways to Create Outlets 372 Table of Contents | vii
  • 14. Outlet Collections 374 Action Connections 375 More Ways to Create Actions 377 Misconfigured Actions 379 Connections Between Nibs — Not! 379 Additional Configuration of Nib-Based Instances 380 8. Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 The Documentation Window 385 Class Documentation Pages 386 Quick Help 390 Symbol Declarations 392 Header Files 393 Sample Code 394 Internet Resources 394 9. Life Cycle of a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Environmental Dependencies 397 Permissible Runtime Environment 398 Backward Compatibility 398 Device Type 400 Arguments and Environment Variables 401 Conditional Compilation 402 Version Control 404 Editing and Navigating Your Code 407 Autocompletion 409 Snippets 410 Fix-it and Live Syntax Checking 412 Navigation 413 Finding 415 Refactoring 416 Running in the Simulator 416 Debugging 417 Caveman Debugging 417 The Xcode Debugger 420 Testing 427 Unit Tests 428 Interface Tests 431 Clean 433 Running on a Device 433 Obtaining a Developer Program Membership 434 Signing an App 435 viii | Table of Contents
  • 15. Automatic Signing 436 Manual Signing 439 Running the App 441 Managing Development Certificates and Devices 442 Profiling 442 Gauges 442 Memory Debugging 444 Instruments 445 Localization 448 Distribution 453 Making an Archive 453 The Distribution Certificate 454 The Distribution Profile 456 Distribution for Testing 457 Final App Preparations 458 Screenshots and Video Previews 461 Property List Settings 463 Submission to the App Store 464 Part III. Cocoa 10. Cocoa Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 Subclassing 469 Categories and Extensions 472 How Swift Uses Extensions 472 How You Use Extensions 473 How Cocoa Uses Categories 473 Protocols 475 Informal Protocols 477 Optional Methods 477 Some Foundation Classes 480 NSRange and NSNotFound 481 NSString and Friends 483 NSDate and Friends 486 NSNumber 487 NSValue 489 NSData 490 NSMeasurement and Friends 491 Equality, Hashability, and Comparison 491 NSArray and NSMutableArray 494 NSDictionary and NSMutableDictionary 496 Table of Contents | ix
  • 16. NSSet and Friends 496 NSIndexSet 497 NSNull 498 Immutable and Mutable 498 Property Lists 500 Codable 501 Accessors, Properties, and Key–Value Coding 504 Swift Accessors 505 Key–Value Coding 507 Uses of Key–Value Coding 508 KVC and Outlets 510 Cocoa Key Paths 510 The Secret Life of NSObject 511 11. Cocoa Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 Reasons for Events 513 Subclassing 514 Notifications 516 Receiving a Notification 517 Unregistering 519 Posting a Notification 520 Timer 521 Delegation 523 Cocoa Delegation 523 Implementing Delegation 525 Data Sources 527 Actions 527 The Responder Chain 530 Deferring Responsibility 531 Nil-Targeted Actions 532 Key–Value Observing 533 Registration and Notification 534 Unregistering 535 Key–Value Observing Example 536 Swamped by Events 537 Delayed Performance 540 12. Memory Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543 Principles of Cocoa Memory Management 543 Rules of Cocoa Memory Management 544 What ARC Is and What It Does 545 How Cocoa Objects Manage Memory 546 x | Table of Contents
  • 17. Autorelease Pool 547 Memory Management of Instance Properties 549 Retain Cycles and Weak References 550 Unusual Memory Management Situations 552 Notification Observers 552 KVO Observers 554 Timers 554 Other Unusual Situations 556 Nib Loading and Memory Management 556 Memory Management of CFTypeRefs 557 Property Memory Management Policies 559 Debugging Memory Management Mistakes 561 13. Communication Between Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563 Visibility by Instantiation 564 Visibility by Relationship 566 Global Visibility 567 Notifications and Key–Value Observing 569 Model–View–Controller 569 A. C, Objective-C, and Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607 Table of Contents | xi
  • 19. 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 consider 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 Swift deserved to be, and probably would be, adopted by new students of iOS programming, and that my books, therefore, should henceforth assume that readers are using Swift. That decision has proven prophetic. Programmers of iOS have flocked to Swift in increasing numbers, and Swift itself has only improved. My iOS apps (such as Diabel‐ li’s Theme, LinkSame, Zotz!, TidBITS News, and my Latin and Greek flashcard apps) have all been rewritten in Swift, and are far easier for me to understand and maintain than their Objective-C originals. Xcode 10 comes with Swift 4.2. The language has evolved greatly in its details and in the nature of its integration with the Cocoa libraries that underlie iOS programming, but its spirit has remained constant. 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. xiii
  • 20. 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. Memory management Swift manages memory automatically. You will rarely have to concern yourself with memory management. Cocoa compatibility The Cocoa APIs are written primarily 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. 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. Still, the reader may 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 might have to know what those lan‐ guages would expect. xiv | Preface
  • 21. Therefore, although I do not attempt to teach Objective-C in this book, I do describe it in enough detail to allow you to read it when you encounter it in the documenta‐ tion and on the Internet, and I occasionally show some Objective-C code. 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 commu‐ nicate with one another, as well as explaining how your app can be written partly in Swift and partly in Objective-C. The Scope of This Book This book is actually one of a pair with my Programming iOS 12, which picks up exactly where this book leaves off. They complement and supplement one another. The two-book architecture should, I believe, render the size and scope of each book tractable for readers. Together, they provide a complete grounding in the knowledge needed to begin writing iOS apps; thus, when you do start writing iOS apps, you’ll have a solid and rigorous understanding of what you are doing and where you are heading. If writing an iOS program is like building a house of bricks, this book teaches you what a brick is and how to handle it, while Programming iOS 12 hands you some actual bricks and tells you how to assemble them. When you have read this book, you’ll know about Swift, Xcode, and the underpin‐ nings of the Cocoa framework, and you will be ready to proceed directly to Program‐ ming iOS 12. Conversely, Programming iOS 12 assumes a knowledge of this book; it begins, like Homer’s Iliad, in the middle of the story, with the reader jumping with all four feet into views and view controllers, and with a knowledge of the language and the Xcode IDE already presupposed. If you started reading Programming iOS 12 and wondered about such unexplained matters as Swift language basics, the UIApplicationMain function, the nib-loading mechanism, Cocoa patterns of delega‐ tion and notification, and retain cycles, wonder no longer — I didn’t explain them there because I do explain them here. The three parts of this book teach the underlying basis of all iOS programming: • 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 Preface | xv
  • 22. Swift playgrounds or the REPL. My focus here is real-life iOS programming, and my explanation of Swift therefore concentrates on those common, practical 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 12, of course! Versions This book is geared to Swift 4.2, iOS 12, and Xcode 10. 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). xvi | Preface
  • 23. A word about method names. I generally give method names in Swift, in the style of a function reference (as described in Chapter 2) — that is, the name plus parentheses containing the parameter labels followed by colon. 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 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 10 under macOS 10.13 High Sierra. I have not upgraded my machine to macOS 10.14 Mojave, 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 running Mojave, your interface may naturally look slightly different from the screenshots (especially if you’re using “dark mode”), but this difference will be minimal and shouldn’t cause any confusion. 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. 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) Preface | xvii
  • 24. • 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. From the Programming iOS 4 Preface A programming framework has a kind of personality, an overall flavor that provides an insight into the goals and mindset of those who created it. When I first encoun‐ tered Cocoa Touch, my assessment of its personality was: “Wow, the people who wrote this are really clever!” On the one hand, the number of built-in interface objects was severely and deliberately limited; on the other hand, the power and flexi‐ bility of some of those objects, especially such things as UITableView, was greatly enhanced over their OS X counterparts. Even more important, Apple created a partic‐ ularly brilliant way (UIViewController) to help the programmer make entire blocks of interface come and go and supplant one another in a controlled, hierarchical man‐ ner, thus allowing that tiny iPhone display to unfold virtually into multiple interface worlds within a single app without the user becoming lost or confused. The popularity of the iPhone, with its largely free or very inexpensive apps, and the subsequent popularity of the iPad, have brought and will continue to bring into the fold many new programmers who see programming for these devices as worthwhile and doable, even though they may not have felt the same way about OS X. Apple’s own annual WWDC developer conventions have reflected this trend, with their emphasis shifted from OS X to iOS instruction. 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. xviii | Preface
  • 25. 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. Conventions Used in This Book The following typographical conventions are used in this book: 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. This element signifies a tip or suggestion. Preface | xix
  • 26. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at http://github.com/mattneub/Programming-iOS-Book-Examples. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “iOS 12 Programming Fundamentals with Swift by Matt Neuburg (O’Reilly). Copyright 2018 Matt Neuburg, 978-1-492-04455-0.” 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]. Safari® Books Online Safari (formerly Safari Books Online) is a membership- based training and reference platform for enterprise, gov‐ ernment, educators, and individuals. Members have access to thousands of books, training videos, Learning Paths, interac‐ tive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐ sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others. xx | Preface
  • 27. For more information, please visit http://oreilly.com/safari. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) 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/ios12-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 Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Preface | xxi
  • 29. 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 programming. • 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,
  • 30. 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 describe Swift access control (privacy), introspection (reflection), and how to create your own opera‐ tors. There follows a discussion of some recently added Swift language features: synthesized protocol implementations, key paths, and dynamic member lookup. The chapter concludes by considering Swift memory management.
  • 31. 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") (The print command provides instant feedback in the Xcode console.) You can combine more than one statement on a line, but then you need to put a semicolon between them: print("hello"); print("world") You are free to put a semicolon at the end of a statement that is last or alone on its line, but no one ever does (except out of habit, because C and Objective-C require the semicolon): print("hello"); print("world"); Conversely, a single statement can be broken into multiple lines, in order to prevent long statements from becoming long lines. But you should try to do this at sensible places so as not to confuse Swift. For example, after an opening parenthesis is a good place: 3
  • 32. 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 runs. The Swift compiler’s error and warning messages, however, 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 occa‐ sional unhelpful nature of its messages. Remember, it knows more than you do, even if it is sometimes rather inarticulate about its knowledge. 4 | Chapter 1: The Architecture of Swift
  • 33. Everything Is an Object? In Swift, “everything is an object.” That’s a boast common to various modern object- oriented languages, but what does it mean? Well, that depends on what you mean by “object” — and what you mean by “everything.” Let’s start by stipulating that an object, roughly speaking, is something you can send a message to. A message, roughly speaking, is an imperative instruction. For example, you can give commands to a dog: “Bark!” “Sit!” In this analogy, those phrases are messages, and the dog is the object to which you are sending those messages. In Swift, the syntax of message-sending is dot-notation. We start with the object; then there’s a dot (a period); then there’s the message. (Some messages are also followed by parentheses, but ignore them for now; the full syntax of message-sending is one of those details we’ll be filling in later.) This is valid Swift syntax: fido.bark() rover.sit() The idea of everything being an object is a way of suggesting that even “primitive” lin‐ guistic entities can be sent messages. Take, for example, 1. It appears to be a literal digit and no more. It will not surprise you, if you’ve ever used any programming lan‐ guage, that you can say things like this in Swift: let sum = 1 + 2 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
  • 34. 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. Three Flavors of Object Type If you know Objective-C or some other object-oriented language, you may be sur‐ prised by Swift’s notion of what kind of object 1 is. In many languages, such as Objective-C, an object is a class or an instance of a class (I’ll explain later what an instance is). Swift has classes, but 1 in Swift is not a class or an instance of a class: the type of 1, namely Int, is a struct, and 1 is an instance of a struct. And Swift has yet another kind of thing you can send messages to, called an enum. So Swift has three kinds of object type: classes, structs, and enums. I like to refer to these as the three flavors of object type. Exactly how they differ from one another will emerge in due course. But they are all very definitely object types, and their similari‐ ties to one another are far stronger than their differences. For now, just bear in mind that these three flavors exist. (The fact that a struct or enum is an object type in Swift will surprise you particularly if you know Objective-C. Objective-C has structs and enums, but they are not objects. Swift structs, in particular, are much more important and pervasive than Objective-C structs. This difference between how Swift views structs and enums and how Objective-C views them can matter when you are talking to Cocoa.) 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 6 | Chapter 1: The Architecture of Swift
  • 35. Once the name exists, you are free to use it. For example, we can change the value of two to be the same as the value of one: let one = 1 var two = 2 two = one 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 Once two is declared and initialized as 2, it is a number (properly speaking, an Int) and it must always be so. You can replace its value with 1 because that’s also an Int, but you can’t replace its value with "hello" because that’s a string (properly speaking, a String) — and a String is not an Int. Variables literally have a life of their own — more accurately, a lifetime of their own. As long as a variable exists, it keeps its value alive. Thus, a variable can be not only a way of conveniently naming something, but also a way of preserving it. I’ll have more to say about that later. Variables | 7
  • 36. By convention, type names such as String or Int (or Dog or Cat) start with a capi‐ tal letter; variable names start with a small letter. Do not violate this convention. If you do, your code might still compile and run just fine, but I will personally send agents to your house to remove your kneecaps in the dead of night. Functions Executable code, like fido.bark() or one = two, cannot go just anywhere in your program. (Failure to appreciate this fact is a common beginner mistake, and can result in a mysterious compile error message such as “Expected declaration.”) In gen‐ eral, executable code must live inside the body of a function. A function is a batch of code that can be told, as a batch, to run. Typically, a function has a name, and it gets that name through a function declaration. Function declaration syntax is another of those details that will be filled in later, but here’s an example: func go() { let one = 1 var two = 2 two = one } That describes a sequence of things to do — declare one, declare two, change the value of two to match the value of one — and it gives that sequence a name, go; but it doesn’t perform the sequence. The sequence is performed when someone calls the function. Thus, we might say, elsewhere: go() That is a command to the go function that it should actually run. But again, that com‐ mand is itself executable code, so it cannot live on its own either. It might live in the body of a different function: func doGo() { go() } But wait! This is getting a little nutty. That, too, is just a function declaration; to run it, someone must call doGo by saying doGo() — and that’s executable code too. This seems like some kind of infinite regression; it looks like none of our code will ever run. If all executable code has to live in a function, who will tell any function to run? The initial impetus must come from somewhere. In real life, fortunately, this regression problem doesn’t arise. Remember that your goal is ultimately to write an iOS app. Thus, your app will be run on an iOS device (or the Simulator) by a runtime that already wants to call certain functions. So you start by writing special functions that you know the runtime itself will call. That gives your app a way to get started and gives you places to put functions that will be called by the 8 | Chapter 1: The Architecture of Swift
  • 37. runtime at key moments — such as when the app launches, or when the user taps a button in your app’s interface. Swift also has a special rule that a file called main.swift, exceptionally, can have executable code at its top level, outside any function body, and this is the code that actually runs when the program runs. You can construct your app with a main.swift file, but in general you won’t need to. The Structure of a Swift File A Swift program can consist of one file or many files. In Swift, a file is a meaningful unit, and there are definite rules about the structure of the Swift code that can go inside it. (I’m assuming that we are not in a main.swift file.) Only certain things can go at the top level of a Swift file — chiefly the following: Module import statements A module is an even higher-level unit than a file. A module can consist of multi‐ ple files, and these can all see each other automatically; but a module can’t see another module without an import statement. For example, that is how you are able to talk to Cocoa in an iOS program: the first line of your file says import UIKit. Variable declarations A variable declared at the top level of a file is a global variable: all code will be able to see and access it, without explicitly sending a message to any object, and it lives as long as the program runs. Function declarations A function declared at the top level of a file is a global function: all code will be able to see and call it, without explicitly sending a message to any object. Object type declarations The declaration for a class, a struct, or an enum. For example, this is a legal Swift file containing (just to demonstrate that it can be done) an import statement, a variable declaration, a function declaration, a class dec‐ laration, a struct declaration, and an enum declaration: import UIKit var one = 1 func changeOne() { } class Manny { } The Structure of a Swift File | 9
  • 38. struct Moe { } enum Jack { } That’s a very silly and mostly empty example, but remember, our goal is to survey the parts of the language and the structure of a file, and the example shows them. Furthermore, the curly braces for each of the things in that example can all have vari‐ able declarations, function declarations, and object type declarations within them! Indeed, any structural curly braces can contain such declarations. You’ll notice that I did not say that executable code can go at the top level of a file. That’s because it can’t! Only a function body can contain executable code. A statement like one = two or print(name) is executable code, and can’t go at the top level of a file. But in our previous example, func changeOne() is a function declaration, so exe‐ cutable code can go inside its curly braces, because they constitute a function body: var one = 1 // executable code can't go here func changeOne() { let two = 2 // executable code one = two // executable code } Executable code also can’t go directly inside the curly braces that accompany the class Manny declaration; that’s the top level of a class declaration, not a function body. But a class declaration can contain a function declaration, and that function declaration can contain executable code: class Manny { let name = "manny" // executable code can't go here func sayName() { print(name) // executable code } } To sum up, Example 1-1 is a legal Swift file, schematically illustrating the structural possibilities. (Ignore the hanky-panky with the name variable declaration inside the enum declaration for Jack; enum top-level variables have some special rules that I’ll explain later.) Example 1-1. Schematic structure of a legal Swift file import UIKit var one = 1 func changeOne() { let two = 2 func sayTwo() { 10 | Chapter 1: The Architecture of Swift
  • 39. print(two) } class Klass {} struct Struct {} enum Enum {} one = two } class Manny { let name = "manny" func sayName() { print(name) } class Klass {} struct Struct {} enum Enum {} } struct Moe { let name = "moe" func sayName() { print(name) } class Klass {} struct Struct {} enum Enum {} } enum Jack { var name : String { return "jack" } func sayName() { print(name) } class Klass {} struct Struct {} enum Enum {} } Obviously, we can recurse down as far we like: we could have a class declaration con‐ taining a class declaration containing a class declaration, and so on. But there’s no point illustrating that. Scope and Lifetime In a Swift program, things have a scope. This refers to their ability to be seen by other things. Things are nested inside of other things, making a nested hierarchy of things. The rule is that things can see things at their own level and at a higher level containing them. The levels are: • A module is a scope. • A file is a scope. Scope and Lifetime | 11
  • 40. • Curly braces are a scope. When something is declared, it is declared at some level within that hierarchy. Its place in the hierarchy — its scope — determines whether it can be seen by other things. Look again at Example 1-1. Inside the declaration of Manny is a name variable decla‐ ration and a sayName function declaration; the code inside sayName’s curly braces can see things outside those curly braces at a higher containing level, and can therefore see the name variable. Similarly, the code inside the body of the changeOne function can see the one variable declared at the top level of the file; indeed, everything throughout this file can see the one variable declared at the top level of the file. Scope is thus a very important way of sharing information. Two different functions declared inside Manny would both be able to see the name declared at Manny’s top level. Code inside Jack and code inside Moe can both see the one declared at the file’s top level. Things also have a lifetime, which is effectively equivalent to their scope. A thing lives as long as its surrounding scope lives. Thus, in Example 1-1, the variable one lives as long as the file lives — namely, as long the program runs. It is global and persistent. But the variable name declared at the top level of Manny exists only so long as a Manny instance exists (I’ll talk in a moment about what that means). Things declared at a deeper level live even shorter lifetimes. Consider this code: func silly() { if true { class Cat {} var one = 1 one = one + 1 } } That code is silly, but it’s legal: remember, I said that variable declarations, function declarations, and object type declarations can appear in any structural curly braces. In that code, the class Cat and the variable one will not even come into existence until someone calls the silly function, and even then they will exist only during the brief instant that the path of code execution passes through the if construct. So, suppose the function silly is called; the path of execution then enters the if construct. Here, Cat is declared and comes into existence; then one is declared and comes into exis‐ tence; then the executable line one = one + 1 is executed; and then the scope ends and both Cat and one vanish in a puff of smoke. And throughout their brief lives, Cat and one were completely invisible to the rest of the program. (Do you see why?) 12 | Chapter 1: The Architecture of Swift
  • 41. Object Members Inside the three object types (class, struct, and enum), things declared at the top level have special names, mostly for historical reasons. Let’s use the Manny class as an example: class Manny { let name = "manny" func sayName() { print(name) } } In that code: • name is a variable declared at the top level of an object declaration, so it is called a property of that object. • sayName is a function declared at the top level of an object declaration, so it is called a method of that object. Things declared at the top level of an object declaration — properties, methods, and any objects declared at that level — are collectively the members of that object. Mem‐ bers have a special significance, because they define the messages you are allowed to send to that object! Namespaces A namespace is a named region of a program. The names of things inside a name‐ space cannot be reached by things outside it without somehow first passing through the barrier of saying that region’s name. This is a good thing because it allows the same name to be used in different places without a conflict. Clearly, namespaces and scopes are closely related notions. Namespaces help to explain the significance of declaring an object at the top level of an object, like this: class Manny { class Klass {} } This way of declaring Klass makes Klass a nested type. It effectively “hides” Klass inside Manny. Manny is a namespace! Code inside Manny can see (and say) Klass directly. But code outside Manny can’t do that. It has to specify the namespace explic‐ itly in order to pass through the barrier that the namespace represents. To do so, it must say Manny’s name first, followed by a dot, followed by the term Klass. In short, it has to say Manny.Klass. Object Members | 13
  • 42. The namespace does not, of itself, provide secrecy or privacy; it’s a convenience. Thus, in Example 1-1, I gave Manny a Klass class, and I also gave Moe a Klass class. But they don’t conflict, because they are in different namespaces, and I can differenti‐ ate them, if necessary, as Manny.Klass and Moe.Klass. It will not have escaped your attention that the syntax for diving explicitly into a namespace is the message-sending dot-notation syntax. They are, in fact, the same thing. In effect, message-sending allows you to see into scopes you can’t see into otherwise. Code inside Moe can’t automatically see the Klass declared inside Manny, but it can see it by taking one easy extra step, namely by speaking of Manny.Klass. It can do that because it can see Manny (because Manny is declared at a level that code inside Moe can see). Modules The top-level namespaces are modules. By default, your app is a module and hence a namespace; that namespace’s name is, roughly speaking, the name of the app. For example, if my app is called MyApp, then if I declare a class Manny at the top level of a file, that class’s real name is MyApp.Manny. But I don’t usually need to use that real name, because my code is already inside the same namespace, and can see the name Manny directly. Frameworks are also modules, and hence they are also namespaces. When you import a module, all the top-level declarations of that module become visible to your code, without your having to use the module’s namespace explicitly to refer to them. For example, Cocoa’s Foundation framework, where NSString lives, is a module. When you program iOS, you will say import Foundation (or, more likely, you’ll say import UIKit, which itself imports Foundation), thus allowing you to speak of NSString without saying Foundation.NSString. But you could say Foundation.NSString, and if you were so silly as to declare a different NSString in your own module, you would have to say Foundation.NSString, in order to differen‐ tiate them. You can also create your own frameworks, and these, too, will be modules. Swift itself is defined in a module — the Swift module. Your code always implicitly imports the Swift module. You could make this explicit by starting a file with the line import Swift; there is no need to do this, but it does no harm either. That fact is important, because it solves a major mystery: where do things like print come from, and why is it possible to use them outside of any message to any object? print is in fact a function declared at the top level of the Swift module, and your code can see the Swift module’s top-level declarations because it imports Swift. The print function thus becomes, as far as your code is concerned, an ordinary top-level func‐ 14 | Chapter 1: The Architecture of Swift
  • 43. tion like any other; it is global to your code, and your code can speak of it without specifying its namespace. You can specify its namespace — it is perfectly legal to say things like Swift.print("hello") — but you probably never will, because there’s no name conflict to resolve. You can actually see the Swift top-level declarations and read and study them, and this can be a useful thing to do. For example, to see the declaration of print, Command-Control-click the term print in your code. Alternatively, explicitly import Swift and Command-Control-click the term Swift. Behold, there are the Swift top-level declarations! You won’t see any executable Swift code here, but you will see the declarations for all the available Swift terms, including top-level functions like print, operators like +, and built-in types such as Int and String (look for struct Int, struct String, and so on). Instances Object types — class, struct, and enum — have an important feature in common: they can be instantiated. In effect, when you declare an object type, you are only defining a type. To instantiate a type is to make a thing — an instance — of that type. So, for example, I can declare a Dog class, and I can give my class a method: class Dog { func bark() { print("woof") } } But I don’t actually have any Dog objects in my program yet. I have merely described the type of thing a Dog would be if I had one. To get an actual Dog, I have to make one. The process of making an actual Dog object whose type is the Dog class is the process of instantiating Dog. The result is a new object — a Dog instance. In Swift, instances can be created by using the object type’s name as a function name and calling the function. This involves using parentheses. When you append paren‐ theses to the name of an object type, you are sending a very special kind of message to that object type: Instantiate yourself! So now I’m going to make a Dog instance: let fido = Dog() There’s a lot going on in that code! I did two things. I instantiated Dog, thus causing me to end up with a Dog instance. I also put that Dog instance into a shoebox called fido — I declared a variable and initialized the variable by assigning my new Dog instance to it. Now fido is a Dog instance. (Moreover, because I used let, fido will always be this same Dog instance. I could have used var instead, but even then, Instances | 15
  • 44. Figure 1-1. Making an instance and calling an instance method initializing fido as a Dog instance would have meant fido could only be some Dog instance after that.) Now that I have a Dog instance, I can send instance messages to it. And what do you suppose they are? They are Dog’s properties and methods! For example: let fido = Dog() fido.bark() That code is legal. Not only that, it is effective: it actually does cause "woof" to appear in the console. I made a Dog and I made it bark! (See Figure 1-1.) There’s an important lesson here, so let me pause to emphasize it. By default, proper‐ ties and methods are instance properties and methods. You can’t use them as mes‐ sages to the object type itself; you have to have an instance to send those messages to. As things stand, this is illegal and won’t compile: Dog.bark() // compile error It is possible to declare a function bark in such a way that saying Dog.bark() is legal, but that would be a different kind of function — a class function or a static function — and you would need to say so when you declare it. The same thing is true of properties. To illustrate, let’s give Dog a name property: class Dog { var name = "" } That allows me to set a Dog’s name, but it needs to be an instance of Dog: 16 | Chapter 1: The Architecture of Swift
  • 45. let fido = Dog() fido.name = "Fido" It is possible to declare a property name in such a way that saying Dog.name is legal, but that would be a different kind of property — a class property or a static property — and you would need to say so when you declare it. Why Instances? Even if there were no such thing as an instance, an object type is itself an object. We know this because it is possible to send a message to an object type (the phrase Manny.Klass is a case in point). Why, then, do instances exist at all? The answer has mostly to do with the nature of instance properties. The value of an instance property is defined with respect to a particular instance. This is where instances get their real usefulness and power. Consider again our Dog class. I’ll give it a name property and a bark method; remem‐ ber, these are an instance property and an instance method: class Dog { var name = "" func bark() { print("woof") } } A Dog instance comes into existence with a blank name (an empty string). But its name property is a var, so once we have any Dog instance, we can assign to its name a new String value: let dog1 = Dog() dog1.name = "Fido" We can also ask for a Dog instance’s name: let dog1 = Dog() dog1.name = "Fido" print(dog1.name) // "Fido" The important thing is that we can make more than one Dog instance, and that two different Dog instances can have two different name property values (Figure 1-2): let dog1 = Dog() dog1.name = "Fido" let dog2 = Dog() dog2.name = "Rover" print(dog1.name) // "Fido" print(dog2.name) // "Rover" Why Instances? | 17
  • 46. Figure 1-2. Two dogs with different property values Note that a Dog instance’s name property has nothing to do with the name of the vari‐ able to which a Dog instance is assigned. The variable is just a shoebox. You can pass an instance from one shoebox to another. But the instance itself maintains its own internal integrity: let dog1 = Dog() dog1.name = "Fido" var dog2 = Dog() dog2.name = "Rover" print(dog1.name) // "Fido" print(dog2.name) // "Rover" dog2 = dog1 print(dog2.name) // "Fido" That code didn’t change Rover’s name; it changed which dog was inside the dog2 shoe‐ box, replacing Rover with Fido. The full power of object-based programming has now emerged. There is a Dog object type which defines what it is to be a Dog. Our declaration of Dog says that a Dog instance — any Dog instance, every Dog instance — has a name property and a bark method. But each Dog instance can have its own name property value. They are differ‐ ent instances and maintain their own internal state. So multiple instances of the same object type behave alike — both Fido and Rover can bark, and will do so when they are sent the bark message — but they are different instances and can have different property values: Fido’s name is "Fido" while Rover’s name is "Rover". 18 | Chapter 1: The Architecture of Swift
  • 47. So an instance is a reflection of the instance methods of its type, but that isn’t all it is; it’s also a collection of instance properties. The object type is responsible for what properties the instance has, but not necessarily for the values of those properties. The values can change as the program runs, and apply only to a particular instance. An instance is a cluster of particular property values. An instance is responsible not only for the values but also for the lifetimes of its prop‐ erties. Suppose we bring a Dog instance into existence and assign to its name property the value "Fido". Then this Dog instance is keeping the string "Fido" alive just so long as we do not replace the value of its name with some other value — and just so long as this instance lives. In short, an instance is both code and data. The code it gets from its type and in a sense is shared with all other instances of that type, but the data belong to it alone. The data can persist as long as the instance persists. The instance has, at every moment, a state — the complete collection of its own personal property values. An instance is a device for maintaining state. It’s a box for storage of data. The Keyword self An instance is an object, and an object is the recipient of messages. Thus, an instance needs a way of sending a message to itself. This is made possible by the keyword self. This word can be used wherever an instance of the appropriate type is expected. For example, let’s say I want to keep the thing that a Dog says when it barks, such as "woof", in a property. Then in my implementation of bark I need to refer to that property. I can do it like this: class Dog { var name = "" var whatADogSays = "woof" func bark() { print(self.whatADogSays) } } Similarly, let’s say I want to write an instance method speak which is merely a syno‐ nym for bark. My speak implementation can consist of simply calling my own bark method. I can do it like this: class Dog { var name = "" var whatADogSays = "woof" func bark() { print(self.whatADogSays) } The Keyword self | 19
  • 48. func speak() { self.bark() } } Observe that the term self in that example appears only in instance methods. When an instance’s code says self, it is referring to this instance. If the expression self.name appears in a Dog instance method’s code, it means the name of this Dog instance, the one whose code is running at that moment. It turns out that every use of the word self I’ve just illustrated is completely optional. You can omit it and all the same things will happen: class Dog { var name = "" var whatADogSays = "woof" func bark() { print(whatADogSays) } func speak() { bark() } } The reason is that if you omit the message recipient and the message you’re sending can be sent to self, the compiler supplies self as the message’s recipient under the hood. However, I never do that (except by mistake). As a matter of style, I like to be explicit in my use of self. I find code that omits self harder to read and understand. And there are situations where you must say self, so I prefer to use it whenever I’m allowed to. Privacy Earlier, I said that a namespace is not, of itself, an insuperable barrier to accessing the names inside it. But such a barrier is sometimes desirable. For example, not all data stored by an instance is intended for alteration by, or even visibility to, another instance. And not every instance method is intended to be called by other instances. Any decent object-based programming language needs a way to endow its object members with privacy — a way of making it harder for other objects to see those members if they are not supposed to be seen. Consider, for example: class Dog { var name = "" var whatADogSays = "woof" func bark() { print(self.whatADogSays) } 20 | Chapter 1: The Architecture of Swift
  • 49. func speak() { print(self.whatADogSays) } } Here, other objects can come along and change my property whatADogSays. Since that property is used by both bark and speak, we could easily end up with a Dog that, when told to bark, says "meow". That seems somehow undesirable: let dog1 = Dog() dog1.whatADogSays = "meow" dog1.bark() // meow You might reply: Well, silly, why did you declare whatADogSays with var? Declare it with let instead. Make it a constant! Now no one can change it: class Dog { var name = "" let whatADogSays = "woof" func bark() { print(self.whatADogSays) } func speak() { print(self.whatADogSays) } } That is a good answer, but it is not quite good enough. There are two problems. Sup‐ pose I want a Dog instance itself to be able to change its own whatADogSays — by assigning to self.whatADogSays. Then whatADogSays has to be a var; otherwise, even the instance itself can’t change it. Also, suppose I don’t want any other object to know what this Dog says, except by calling bark or speak. Even when declared with let, other objects can still read the value of whatADogSays. Maybe I don’t like that. To solve this problem, Swift provides the private keyword. I’ll talk later about all the ramifications of this keyword, but for now it’s enough to know that it solves the problem: class Dog { var name = "" private var whatADogSays = "woof" func bark() { print(self.whatADogSays) } func speak() { print(self.whatADogSays) } } Now name is a public property, but whatADogSays is a private property: it can’t be seen by other types of object. A Dog instance can speak of self.whatADogSays, but a Cat Privacy | 21
  • 50. Reserved Words Certain terms, like class and func and var and let and if and private and import, are reserved in Swift; they are part of the language. That means you can’t use them as identifiers — as the name of a class, a function, or a variable, for example. If you try to do so, you’ll get a compile error. To force a reserved word to be an identifier, surround it by backticks (`). This (extra‐ ordinarily confusing) code is legal: class `func` { func `if`() { let `class` = 1 } } instance with a reference to a Dog instance as fido cannot say fido.whatADogSays. The important lesson here is that object members are public by default, and if you want privacy, you have to ask for it. To sum up: A class declaration defines a namespace. This namespace requires that other objects use an extra level of dot-notation to refer to what’s inside the name‐ space, but other objects can still refer to what’s inside the namespace; the namespace does not, in and of itself, close any doors of visibility. The private keyword lets you close those doors. Design What object types will your program need, what methods and properties should they have, when and how will they be instantiated, and what should you do with those instances when you have them? Those aren’t easy decisions, and there are no clear-cut answers. Object-based programming is an art. In real life, when you’re programming iOS, many object types you’ll be working with will not be yours but Apple’s. Swift itself comes with a few useful object types, such as String and Int; you’ll also import UIKit, which includes a huge number of object types, all of which spring to life in your program. You didn’t create any of those object types, so their design is not your problem; instead, you must learn to use them. Apple’s object types are aimed at enabling the general functionality that any app might need. At the same time, your app will probably have specific functionality, unique to its purpose, and you will have to design object types to serve that purpose. Object-based program design must be founded upon a secure understanding of the nature of objects. You want to design object types that encapsulate the right sort of functionality (methods) accompanied by the right set of data (properties). Then, 22 | Chapter 1: The Architecture of Swift
  • 51. when you instantiate those object types, you want to make sure that your instances have the right lifetimes, sufficient exposure to one another, and an appropriate ability to communicate with one another. Object Types and APIs Your program files will have very few, if any, top-level functions and variables. Meth‐ ods and properties of object types — in particular, instance methods and instance properties — will be where most of the action is. Object types give each actual instance its specialized abilities. They also help to organize your program’s code meaningfully and maintainably. We may summarize the nature of objects in two phrases: encapsulation of functional‐ ity, and maintenance of state. (I first used this summary many years ago in my book REALbasic: The Definitive Guide.) Encapsulation of functionality Each object does its own job, and presents to the rest of the world — to other objects, and indeed in a sense to the programmer — an opaque wall whose only entrances are the methods to which it promises to respond and the actions it promises to perform when the corresponding messages are sent to it. The details of how, behind the scenes, it actually implements those actions are secreted within itself; no other object needs to know them. Maintenance of state Each individual instance is a bundle of data that it maintains. Often that data is private, so it’s encapsulated as well; no other object knows what that data is or in what form it is kept. The only way to discover from outside what private data an object is maintaining is if there’s a public method or property that reveals it. As an example, imagine an object whose job is to implement a stack — it might be an instance of a Stack class. A stack is a data structure that maintains a set of data in LIFO order (last in, first out). It responds to just two messages: push and pop. Push means to add a given piece of data to the set. Pop means to remove from the set the piece of data that was most recently pushed and hand it out. It’s like a stack of plates: plates are placed onto the top of the stack or removed from the top of the stack one by one, so the first plate to go onto the stack can’t be retrieved until all other subse‐ quently added plates have been removed (Figure 1-3). The stack object illustrates encapsulation of functionality because the outside world knows nothing of how the stack is actually implemented. It might be an array, it might be a linked list, it might be any of a number of other implementations. But a client object — an object that actually sends a push or pop message to the stack object — knows nothing of this and cares less, provided the stack object adheres to its con‐ tract of behaving like a stack. This is also good for the programmer, who can, as the Design | 23
  • 52. Figure 1-3. A stack program develops, safely substitute one implementation for another without harming the vast machinery of the program as a whole. The stack object illustrates maintenance of state because it isn’t just the gateway to the stack data — it is the stack data. Other objects can get access to that data, but only by virtue of having access to the stack object itself, and only in the manner that the stack object permits. The stack data is effectively inside the stack object; no one else can see it. All that another object can do is push or pop. The sum total of messages that each object type is eligible to be sent by other objects — its API (application programming interface) — is like a list or menu of things you can ask this type of object to do. Your object types divide up your code; their APIs form the basis of communication between those divisions. The same is true of objects that you didn’t design. Apple’s Cocoa documentation consists largely of lists of object APIs. For example, to know what messages you can send to an NSString instance, you’d start by studying the NSString class documentation. That page is really just a big list of properties and methods, so it tells you what an NSString object can do — 24 | Chapter 1: The Architecture of Swift
  • 53. and thus constitutes the bulk of what you need to know in order to use NSStrings in your program. Instance Creation, Scope, and Lifetime The important moment-to-moment entities in a Swift program are mostly instances. Object types define what kinds of instances there can be and how each kind of instance behaves. But the actual instances of those types are the state-carrying indi‐ vidual “things” that the program is all about, and instance methods and properties are messages that can be sent to instances. So there need to be instances in order for the program to do anything. By default, however, there are no instances! Looking back at Example 1-1, we defined some object types, but we made no instances of them. If we were to run this program, our object types would exist from the get-go, but that’s all that would exist. We’ve cre‐ ated a world of pure potentiality — some types of object that might exist. In that world, nothing would actually happen. Instances do not come into being by magic. You have to instantiate a type in order to obtain an instance. Much of the action of your program, therefore, will consist of instantiating types. And of course you will want those instances to persist, so you will also assign each newly created instance to a variable as a shoebox to hold it, name it, and give it a lifetime. The instance will persist according to the lifetime of the variable that refers to it. And the instance will be visible to other instances according to the scope of the variable that refers to it. Much of the art of object-based programming involves giving instances a sufficient lifetime and making them visible to one another. You will often put an instance into a particular shoebox — assigning it to a particular variable, declared at a certain scope — exactly so that, thanks to the rules of variable lifetime and scope, this instance will persist long enough to keep being useful to your program while it will still be needed, and so that other code can get a reference to this instance and talk to it later. Planning how you’re going to create instances, and working out the lifetimes and communication between those instances, may sound daunting. Fortunately, in real life, when you’re programming iOS, the Cocoa framework itself will provide an initial scaffolding for you. Before you write a single line of code, the framework ensures that your app, as it launches, is given some instances that will persist for the lifetime of the app, providing the basis of your app’s visible interface and giving you an initial place to put your own instances and give them sufficiently long lifetimes. Summary and Conclusion As we imagine constructing an object-based program for performing a particular task, we bear in mind the nature of objects. There are types and instances. A type is a Design | 25
  • 54. set of methods describing what all instances of that type can do (encapsulation of functionality). Instances of the same type differ only in the value of their properties (maintenance of state). We plan accordingly. Objects are an organizational tool, a set of boxes for encapsulating the code that accomplishes a particular task. They are also a conceptual tool. The programmer, being forced to think in terms of discrete objects, must divide the goals and behaviors of the program into discrete tasks, each task being assigned to an appropriate object. At the same time, no object is an island. Objects can cooperate with one another, namely by communicating with one another — that is, by sending messages to one another. The ways in which appropriate lines of communication can be arranged are innumerable. Coming up with an appropriate arrangement — an architecture — for the cooperative and orderly relationship between objects is one of the most challeng‐ ing aspects of object-based programming. In iOS programming, you get a boost from the Cocoa framework, which provides an initial set of object types and a practical basic architectural scaffolding. Using object-based programming effectively to make a program do what you want it to do while keeping it clear and maintainable is itself an art; your abilities will improve with experience. Eventually, you may want to do some further reading on effective planning and construction of the architecture of an object-based program. I recommend in particular two classic, favorite books. Refactoring, by Martin Fowler (Addison-Wesley, 1999), describes why you might need to rearrange what methods belong to what classes (and how to conquer your fear of doing so). Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (also known as “the Gang of Four”), is the bible on architecting object-based programs, listing all the ways you can arrange objects with the right powers and the right knowledge of one another (Addison-Wesley, 1994). 26 | Chapter 1: The Architecture of Swift
  • 55. Exploring the Variety of Random Documents with Different Content
  • 56. Five days afterwards, on the 26th, there was a recurrence of the typhoon, which the Nemesis rode out very easily in the Typa anchorage at Macao; but it was not so severe as the first one, and comparatively little injury was caused by it. There is reason to believe also, that, had all the ships at Hong-Kong been moored in proper berths, and early precautions taken, before the commencement of the first typhoon, the danger and the damage inflicted would have been much less severe. No time was lost in refitting the ships, and preparations were now hastened for the advance of our forces upon Amoy, and for pushing on our operations further northward, while the favourable season lasted. Sir Gordon Bremer had returned from Calcutta, in the Queen steamer, on the 18th of June, having been invested with the functions of joint-plenipotentiary, in conjunction with Captain Elliot. This high honour was, however, of short duration; for, on the 9th of August, Sir Henry Pottinger arrived from England, via Bombay, having been appointed sole plenipotentiary and chief-superintendent of trade in China: he was accompanied by Vice-Admiral Sir William Parker, by whom all the subsequent naval operations were conducted.
  • 57. CHAPTER XXVI. At the end of July, the H.C. steamer Phlegethon, Lieut. M'Cleverty, nearly the exact counterpart of the Nemesis, arrived at Hong-Kong, bringing the intelligence that Captain Elliot's treaty of Chuenpee had been disapproved of by the home government, and that Sir Henry Pottinger had been appointed to succeed him, as sole plenipotentiary. Shortly before this, also, her Majesty's 55th regiment had arrived from Calcutta, and everything indicated that a movement upon Amoy would take place as soon as possible, after the expected arrival of Sir Henry Pottinger as plenipotentiary, and Sir William Parker as admiral. The season for active operations was already advanced, and even for the sake of the health of the troops, it was the anxious wish of all the officers that a change of some sort or other might speedily take place. In the afternoon of the 10th of August, the arrival of the H.C. steamer Sesostris, from Bombay, in the Macao roads, was announced, and great was the joy of every one when it was made known that both Sir Henry Pottinger and Sir William Parker were on board. They had come from London in the wonderfully short period of sixty-seven days, ten of which had been spent in Bombay. At daylight next morning, the Nemesis went out to convey these high functionaries from the Sesostris, in the roads, to the town of Macao, where they were received with every demonstration of respect, under a salute from the Portuguese forts. A conference was held in the course of the morning, between Captain Elliot and Sir Henry Pottinger, together with the Admiral and Sir Hugh Gough. Energetic measures appeared to be at once resolved on. Sir William Parker went over to visit the fleet at Hong-Kong, and as soon as visits of ceremony had been exchanged between the new plenipotentiary and the Portuguese authorities, Sir Henry Pottinger
  • 58. lost no time in publishing the notification of his appointment, as minister extraordinary and sole plenipotentiary, and also as chief superintendent of trade in China. In order to communicate officially to the Chinese authorities the fact of his arrival, and the nature of his powers, Sir Henry now despatched his secretary, Major Malcolm, to Canton, as the bearer of letters to the provincial government. The Nemesis was, as usual, employed to carry the officers up the river. No little sensation was created among the Chinese officials by the announcement which was now made to them. They therefore resolved to welcome the plenipotentiary with all ceremony; and probably, also, in the hope of being able to form some estimate of his character, they despatched the prefect of the city, or kwang-chow-foo, on the 18th, to Macao, with a numerous retinue. He landed at Macao, upon the Praya Grande, near the governor's palace, attended by a great number of followers, and proceeded in state to the residence of the plenipotentiary, thinking, no doubt, that he was conferring a great honour upon his Excellency, and that he would accordingly be received with every mark of distinction. Alas, how are the mighty fallen! The ceremonious prefect was not even received. He, who had hitherto been courted as an officer of distinction, and had been the medium of communication, and in some sort the ambassador, between the high Chinese authorities and Captain Elliot, was now absolutely rejected. Sir Henry Pottinger, acting with an intimate knowledge of the Oriental character, and fully impressed with the high duties he was called upon to perform, and the high station he had to maintain as her Majesty's representative, declined to receive or hold any direct intercourse with an officer inferior to himself in rank and responsibility, and still less with one of comparatively inferior grade, such as the Prefect of Canton. Major Malcolm, the secretary of legation, was, however, deputed to receive the prefect; and, after a short interview, the would-be great man withdrew, and returned in some dismay to Canton, to report the circumstances to his superiors. The sensation created by this little characteristic incident was very remarkable. It became the
  • 59. subject of conversation in every quarter, and tended to awaken much greater respect for the dignity of the new plenipotentiary. The same cautious and dignified bearing was maintained with the greatest advantage throughout the whole of our subsequent proceedings. At Hong-Kong, the most active preparations were now being made for the immediate departure of the expedition. Excellent arrangements were introduced by Sir William Parker for the proper guidance of the fleet, and especially for the distribution and management of the numerous transports and store-ships. The advantage of this systematic regularity soon became evident; and it is deserving of notice that, from this period to the close of the war, the transport service was conducted with the utmost regularity and efficiency, in spite of the endless difficulties arising out of our imperfect knowledge of the coast of China, and the inaccuracy of most of the charts. Add to this, that owing to sickness and other causes, the transports were often under-manned, and had frequently the most arduous duties to perform. By a general order of the 19th of August, issued only nine days after the arrival of the admiral, the fleet was directed to be ready to put to sea at daylight on the 21st. It was to be formed in three divisions: the centre commanded by Captain Herbert, in the Blenheim, assisted by Commander Clarke, of the Columbine; the starboard division, under Captain Bourchier, in the Blonde, assisted by Commander Gifford, in the Cruiser; while the second, or port division, was placed under Captain Smith, of the Druid, assisted by Commander Anson, of the Pylades. The whole fleet consisted of thirty-six sail, including transports— namely, two line-of-battle ships, the Wellesley and the Blenheim; seven other ships of war—namely, the Modeste, Druid, Columbine, Blonde, Pylades, Cruiser, and Algerine; the Rattlesnake troop-ship, and the Bentinck surveying vessel; four steamers belonging to the East India Company—namely, the Queen, Phlegethon, Nemesis, and Sesostris; and twenty-one hired transports and store-ships, most of
  • 60. them of large size, several of not less than a thousand tons burden. The force stationed in the neighbourhood of the Canton river comprised five or six vessels of war, including the Herald and Alligator, and was under the command of Captain Nias, senior officer. Early on the morning of the 21st, the fleet got under weigh. Sir Henry Pottinger came over from Macao, in The Queen, on that day, just as the fleet had sailed; and, as he stopped some time at Hong- Hong to inspect the place, and examine the various arrangements which had already been made, he did not join the admiral until the following day. The general rendezvous, in case of separation, was to be Chapel Island, not far from Amoy. The weather was extremely favourable during the whole passage up, and, on the 25th, the whole squadron reached the outer harbour of Amoy, having preserved the order of sailing remarkably well throughout. The late plenipotentiaries, Captain Elliot and Sir Gordon Bremer, sailed from Hong-Kong, and finally took leave of China, three days after the departure of the expedition, on board the Atalanta steamer, which had become completely knocked up by her work in the Canton river. Their intention was to proceed as quickly as possible to England, by way of Bombay. The distance of Amoy from Hong-Kong is scarcely three hundred miles, and there were many good grounds for making it the first point of attack, as the expedition proceeded northward. It could not be doubted that the capture of this flourishing commercial city would be seriously felt by the Chinese government. The authorities had, within the last twelve months, spent enormous sums of money and incredible labour in the construction of batteries, which they deemed impregnable, and which were certainly capable of being stoutly defended. The harbour of Amoy is situated in the south-western corner of an island of the same name, which, together with another called Quemoy, occupies a considerable portion of a large bay, in which, however, there are also numerous smaller islands. Of these, the most interesting, in connexion with our present subject, is that of
  • 61. Kolingsoo, which is separated from Amoy by a narrow passage, leading directly up to the harbour. In fact, the possession of this island, which we still retain, gives us the complete command of Amoy itself, or rather of its town and suburbs. The scenery within the bay and about the town of Amoy is exceedingly picturesque, the appearance of the country being very mountainous and striking. Several considerable rivers pour their waters into the bay, and facilitate the communications with the interior of the country. The superiority of the harbour much exceeded the expectations of the officers. The town of Amoy, although possessed of great commercial importance, and very wealthy, is by no means a first-class city—it ranks, indeed, only as a principal third-class town—but its inhabitants are exceedingly enterprising and intelligent, and are remarkable for a certain disposition for emigration and colonization, as well as for their love of commerce. They were the principal colonizers of the flourishing island of Formosa, which lies opposite Amoy, extending itself along the coast for a distance of little less than two hundred miles; and they are to be found in great numbers in more remote islands, subject even to foreign dominion, such as Java, Singapore, Manilla, &c. The city and suburbs of Amoy can hardly be less than eight or ten miles in circumference, and they are in a great degree commanded by a fortified hill or citadel in the rear, which, however, is again commanded (as is very commonly the case in China) by unfortified heights beyond it to the eastward. The suburbs, or outer town, are separated from the principal or inner town by a line of steep, rocky hills, which run transversely down to the beach; but a paved road or narrow causeway leads into the city, through a pass which is protected by a covered gateway at its summit. As there is, therefore, what may be called a double town, so is there also a sort of double harbour—the outer one running along the face of the outer town, and the inner one extending along the front of the principal town, and joining a large estuary, which runs deep into the island across
  • 62. its centre, and skirts the northern side of the city. In this manner, nearly two-thirds of the city of Amoy are washed by the sea. In fact, it stands upon a corner or tongue of land, having a line of bold mountains in its rear and on its flank. The walls are castellated at top, and vary in height, according to the nature of the ground, from twenty to thirty feet. There are also, as in other places, four principal gates, having each an outwork or outer wall, with a court or open space between them, and a second gate leading from this, and placed at right angles to the inner one, so that the approach to it from the outside is commanded by the principal wall of the town. The citadel of Amoy was afterwards found to contain a large supply of military accoutrements—ginjals, matchlocks, swords, shields, and spears of all kinds; there was also an immense quantity of gunpowder, and materials for making it; in short, there was every reason to believe that Amoy had been made use of as the great military depôt of the province. It is impossible to form even a tolerable estimate of the number of troops collected for the defence of the place, but the different accounts which were received varied from six thousand to eight or ten thousand men. It was also known that the high officers of the province had come down to Amoy purposely to encourage the defence, and to witness, as they hoped, the utter discomfiture of the barbarians. It was, however, upon their newly-constructed works that they placed their great reliance. Numerous forts and field-works had been erected upon nearly all the smaller islands which stretch across the mouth of the great bay; and upon the island of Amoy itself a succession of batteries and field- works had been built to command the approach to the town. The principal of these was a long stone battery, well built of granite, faced with earth, extending along the shore nearly up to the suburbs of the city, and designed to command the passage to the harbour. It presented a line of guns a full mile in length, the embrasures being covered with large slabs of stone protected by earth heaped upon them, and mounting no less than ninety-six guns. In the rear of this
  • 63. battery there was a range of steep, rocky heights, up the side of which the Chinese had carried a strong castellated wall to serve as a flanking defence to the battery. Still further to defend the approaches to the city, they had also strongly fortified the little island of Kolingsoo, between which and Amoy the passage is not more than six hundred yards across; this island is, in fact, the key of Amoy, and was retained in our possession when the city and the island of Amoy were restored to the Chinese. At that time the Chinese had already mounted upon the works, either completed or in progress, no less than seventy-six guns. Indeed they had spared no labour to endeavour to render Amoy capable of easy defence; although, from want of skill and discipline, the resistance which they offered was comparatively trifling. If the number of guns alone could indicate the strength of a place, the Chinese might have had some grounds for confidence; for, as Sir Hugh Gough remarked, "every island, every projecting headland whence guns could be made to bear, was occupied and strongly armed." In fact, there were altogether not less than five hundred guns captured at Amoy and the adjacent islands. Early on the morning of the 26th of August, everything was in readiness for the projected attack. The captains and commanders repaired on board the flag-ship for orders; the steamers were all smoking and blowing off their spare steam, and the officers were all anxiously looking for the expected signal to stand in and engage the batteries. Before active operations commenced, however, it was thought right to make a reconnoissance of the defences which were to be attacked. With this view Sir Hugh Gough, Sir William Parker, and the plenipotentiary, stood in on board the Phlegethon, and were able to approach sufficiently close to the works to observe all that was necessary, without having a single shot fired at them. In the meantime a messenger, supposed to be a Chinese merchant, came off from the town, under a flag of truce, requesting to know the object of the visit of so large and formidable a squadron. The answer to this question was simple enough, and was sent in the
  • 64. name of the plenipotentiary, the general, and the admiral, to the effect that "they required that the demands made last year at Tientsin, (near Pekin,) by Captain Elliot, should be complied with; and that hostile measures would, if necessary, be adopted to enforce them. Nevertheless, that as the plenipotentiary and the commanders-in-chief were moved by compassionate feelings, and were unwilling to cause the death of so many officers and soldiers as must perish, they were willing to allow all the officers and troops in the town to retire with their personal arms and baggage, in order to save the people from being hurt, upon condition that the town and fortifications of Amoy should be at once delivered into the hands of the British forces, to be held for the present by them." A white flag was to be exhibited from the fortifications, if these terms were acceded to; otherwise, hostilities would commence. As might be expected, the white flag was not displayed. The morning was very hot and sultry; but about one o'clock a steady, favourable breeze set in, and the squadron got under weigh. The plan was, to make a simultaneous attack upon all the batteries at once, both against those upon Amoy and those upon Kolingsoo. The troops were also to be landed, with the object of taking the batteries in the rear; and the Nemesis and Phlegethon steamers were to be employed to convey them to the appointed place of debarkation. The ships were likely to bear the chief brunt of the engagement; but Sir Hugh Gough made every disposition for the employment of the land forces, and his general order, issued just before the attack was to take place, deserves especial notice. He directed his remarks very strongly to the question of plundering; and observed, that "as Amoy was a large commercial port, and there had once been an English factory there, it was highly important that no act should be committed which could tend to embarrass our future friendly intercourse. The government and the military were to be overcome, and public property taken possession of, under certain instructions, but private property was to be held inviolable; and that which in England," observed the general, "obtains the name of robbery,
  • 65. deserves no better name in China." The camp followers were made liable to be put to death for plundering; and orders were issued to punish on the spot any man straggling from his corps. This alone will suffice to point out that the expedition was very far from possessing that buccaneering character which some persons, particularly foreigners, attempted to cast upon it. Indeed, it may safely be asserted, that war was never carried on with so little infliction of suffering upon the people generally as in China. Generally speaking, the people soon learned to appreciate our motives; and unless prevented by their own officers, they commonly shewed a friendly, or at all events a neutral feeling towards us. Besides the English, the privilege of trading at Amoy was formerly held by the Spanish also; and, at no very remote period, a regular intercourse was kept up between Amoy and the Spanish colony of Manilla. It was probable that the nature of the country round Amoy would render brigade movements inadmissible; but the troops were to be prepared to form in three brigades, if necessary. The men were to land in jackets, caps, and coats folded; and were to carry, each man, one day's cooked provisions. The artillery were to be in readiness to land their light, mountain guns. About half-past one, the attack commenced on our side; but the Chinese had already begun the engagement, by firing occasional shots at our ships, as they proceeded with a steady and favourable breeze to their respective stations. The Sesostris and Queen steamers led in; the former commencing the action, but receiving a heavy fire before she returned it. The line-of-battle ships, Wellesley and Blenheim, under Captains Maitland and Herbert, proceeded to the extremity of the long stone battery, nearest the suburbs, where they anchored by the stern, about half-past two P.M., within four hundred yards of the works, and at once opened a heavy fire upon the principal battery. The next in order along the front of these works, from the suburbs towards the outer extremity, were the Pylades, Columbine, Cruiser,
  • 66. and Algerine. Simultaneously with this attack upon Amoy, the Blonde, Druid, and Modeste, reached their allotted stations, against the works of Kolingsoo; but, owing to the shallowness of the water, they were boldly carried on, in little more than their own draught. The roar of the artillery on every side, echoed by the mountains around, was now terrific; and in one hour and twenty minutes the three principal batteries on Kolingsoo were silenced, and the marines under Captain Ellis, about one hundred and seventy in number, were landed on that island, and took possession of the heights in the rear, without any loss. Three companies of the 26th regiment had also been appointed to this service, but the distance of the transports only permitted a small detachment of them, under Major Johnstone, to land in time to assist in clearing the batteries. The small detachment of the Royal Artillery, under Lieut. the Hon. R. E. Spencer, were actively employed on board the Blonde, during the attack. While these operations were being carried on against the batteries on Kolingsoo, and against the long battery on Amoy, the Phlegethon and Nemesis were speedily brought up with the troops ready to land. The Nemesis had taken on board the general and his staff, together with the 18th Royal Irish, under Colonel Adams; and had also to tow up a number of boats, with the sappers and miners, followers, &c. Considerable delay was therefore occasioned by having to run up to the different transports to embark detachments, and also to pick up the boats; and it was not until half-past three that the Nemesis could get into action. She then opened fire at the long battery with her heavy guns and rockets, as she approached the lower angle of the fort for the purpose of landing the troops. It was just about this time, that as the Phlegethon was also running up towards the battery, a boat was despatched by Lieut. M'Cleverty, in which Lieut. Crawford volunteered his services to capture a small outwork upon a hill, very near the beach; and it was here that the British flag was first displayed upon the enemy's works, on that day, with three cheers from the steamers.
  • 67. About a quarter before four, the general landed upon the beach, near the flank of the great battery, with the 18th and 49th regiments, which were carried in by the Nemesis and Phlegethon steamers. The disembarkation was conducted by Commander Giffard, of the Cruiser. The 18th was directed to escalade the castellated wall which flanked the battery; and, as already described, ran up the hill-side from the beach, nearly at right angles to it. At the same time, the 49th were to move along the beach towards the lower angle of the battery, and either get over it at its sea-face, or force their way through the embrasures. A smart fire was kept up from the Nemesis, to cover the landing and advance of the troops; and Capt. Hall himself, anxious to take an active part in every operation, pushed off from the steamer, in the pinnace manned and armed, accompanied by the unfortunate Mr. Gully, who, as an old and brave friend, volunteered to go with him. This was the same gentleman who afterwards fell a victim to the rapacity and cruelty of the Chinese authorities on the island of Formosa, upon which he had the misfortune to be wrecked, and, after seven months' imprisonment and cruel treatment, was at length executed, together with nearly all his companions. As soon as Capt. Hall and his friend had landed with the pinnace's crew, they joined the advanced guard of the 18th, under Major Tomlinson and Lieut. Murray, who were advancing towards the lower end of the castellated wall. The Chinese opened a smart fire of ginjals and matchlocks as they approached, which was returned by the advancing party, who took advantage of the numerous little hillocks and tombs which lay in their way, to shelter themselves while they reloaded. The Chinese, finding their enemy pressing up towards the wall, and being already bewildered by the admirable firing of the ships, now began to slacken their fire. The 18th rushed for the lower end of the wall, while the party from the Nemesis made a dash at its flank, some way higher up, near a gateway, where the wall appeared less elevated and more accessible. They had, however, brought no
  • 68. scaling-ladders, and, in order to get over the wall, the men were obliged to be lifted up on each other's backs. In this way Captain Hall managed to get first upon the top of the wall, and instantly waved the British flag (which on such occasions he always carried with him in his pocket) in token of triumph. Others soon followed; and the Chinese, the moment they saw their enemies upon the walls, fired two or three random shots, and fled. At this time also the 18th got over the wall lower down, while the 49th forced their way through the embrasures, just at the angle of the sea-face of the great battery. The fire of the ships had not yet ceased, when the party from the Nemesis got down into the body of the fort, and several of our large shot fell close around them. A very short distance in advance they now observed that two Chinese officers of high rank, mounted on horseback, were endeavouring to make their escape, surrounded by a numerous body-guard, or retinue. The opportunity for trying to take an important prisoner was a tempting one; and Captain Hall, little thinking how few of his own men were near him, and carried away by the impulse of the moment, rushed headlong upon the Chinese soldiers in front of him, firing off his pistols at the two principal officers. Only two of his own men were near him at the moment; so that one of the inferior Chinese officers, seeing the disparity, rallied a few of his men, and suddenly faced about, with a view to cut them off. A personal encounter now took place with the Chinese officer, who was a remarkably fine young man, bearing the white button. The long sword, however, soon had the advantage over the Chinese short one, even putting aside personal prowess, and the mandarin fell severely wounded in the arm. He was immediately disarmed, and his cap and button, together with his sword, were taken from him as trophies. Several other soldiers now came up, to endeavour to rescue their officer, who got up and tried to escape, but another wound in the leg soon brought him down again, and made the other Chinamen halt. By this time, Captain Hall and his two men were nearly surrounded, and were compelled to fight their way back again towards their
  • 69. comrades, who were coming up to their aid. One of the two seamen received a severe wound in the groin from the thrust of a spear, but the others got off without any injury. The young wounded mandarin was at last safely carried off by his comrades. The Chinese were now in full flight in every direction, followed by the 18th, 49th, and a party of small-arm men, who were landed from the Wellesley and Blenheim, some way up the sea-face of the fort, under Commander Fletcher and other officers of those ships. The fort was soon completely in our possession. During all the operations of this day, Sir Henry Pottinger and suite were with the admiral on board the Wellesley. On examining the sea-face of the battery, it was impossible not to be struck with the amazing solidity of the wall. It was composed of hewn granite, faced outside with earth, and of such strength, that the heavy firing of two line-of-battle ships against it, at the distance of only four hundred yards, had made very little impression; indeed, it might be said to be shot-proof. The embrasures were something like low port-holes, covered with stone and earth, and in the space between them were sheds, or a sort of temporary watch-boxes, in which was found a quantity of arms of every kind, clothes, half- cooked food, and also opium, with the common pipes used for smoking it. A horse also was found. The guns were many of them very ill-mounted, and in general the carriages were badly contrived, and often defective. In some places you saw bags of sand placed upon the top of the guns, to prevent them from jumping out of the carriages altogether. The fort had evidently been armed hastily. Several high Chinese officers fell during this day; some probably by their own hands. One of them very quietly rushed into the water and drowned himself, although, in the report of the affair to the emperor, it was afterwards stated that he "rushed on to drive back the assailants as they landed, and fell into the water and died." This officer was the Chinese commodore, who commanded in the absence of the admiral. This officer had left the port just before our arrival, (boasting that he was going to meet the barbarians,) and,
  • 70. having sailed northward, could not get back again, owing to the contrary wind. Before five o'clock, the whole of the outer defences of Amoy were in our possession. The Blonde and Modeste, as soon as they had silenced the batteries on Kolingsoo, with the assistance of the Druid, had pushed on into the inner harbour, and captured twenty-six war- junks, mounting not less than one hundred and twenty-eight guns; they were nearly ready for sea, but were deserted by their crews. A large building-yard was discovered, with an immense quantity of timber collected in it; and there was a good-sized frigate-junk, of about three hundred tons, in course of building, in a regular dry dock, something after the European model; they had evidently made a great step in advance in the art of ship-building; indeed, the longer the war lasted, the more the Chinese found themselves led on, by the "impulse of necessity," to attempt great changes, and, in many respects, improvements, not only in their vessels, but in their warlike weapons, and other matters relating to the art of defence. The Nemesis, in running along the shore to avoid the swell which was setting in, unexpectedly found herself within a circular patch of coral rock, which was not visible above the surface. Several fruitless attempts were made to extricate her from this curious position, but the entrance by which she had got into it could not again be found; but her draught of water being very small, it was thought likely she would be able to force her way over the reef without suffering much damage to her iron hull, and she dashed at it at half speed. The blow, however, was more severe than was expected; the vessel bounded completely over the reef; but the sharp coral rock cut completely through her bottom, making a considerable leak in the engine-room. This was fortunately stopped from the inside without much difficulty, and no further notice was taken of it until some time afterwards, when she arrived at Chusan, where the damage was substantially repaired. In the meantime, Sir Hugh Gough pushed on without delay, to occupy a chain of steep, rocky hills, which, running transversely
  • 71. down to the beach, lay between the great fort and the town, so as to intercept the view of the latter. A strong body of the Chinese seemed disposed to defend this position, which was naturally of great strength, and completely commanded the approach to the city. Immediate advantage was to be taken of the prevailing panic; and the 18th and 49th regiments being directed to advance partly up a steep gorge, and partly by a more circuitous road leading round the hills, soon made themselves masters of the heights overlooking the city. The Chinese retreated before them as soon as they had fired off their guns and matchlocks. Our troops bivouacked for the night upon the positions they occupied; but they might have been a good deal harassed by the Chinese, if the latter had taken advantage of the rocky, broken character of the ground, to dispute their further advance. The night was bitterly cold upon the heights. At daylight a reconnoissance was made, and it was soon discovered that little resistance was to be expected. Great confusion and bustle were apparent in all directions; hundreds of the inhabitants were hurrying out of the northern gate, carrying with them their most valuable property; in fact, there was evidently a general panic. Without loss of time, therefore, the 18th, supported by the 49th, were ordered to march down towards the city in the direction of the eastern gate, which was the nearest, while Captain Cotton, the commanding engineer, was directed to examine carefully the approaches to the gate itself. The advanced party of the 18th, on arriving at the gate, found that there was no preparation for resistance, and soon scaled the walls by means of some ladders which were very opportunely found not far from the gate. Heaps of rubbish, and sacks full of earth and sand, were found piled up inside against the gate, so that some time was required to get it open. It was now discovered that the authorities and all the soldiers had abandoned the town, leaving everything in the utmost disorder, so that the only protection which the more respectable and peaceably-inclined inhabitants had to look for, from the violence and plundering of their own rabble, was from the presence of our own troops, and the military government of the
  • 72. city by the victorious captors. Already the mob had begun to ransack some of the public establishments before we found out where they were situated; and it was afterwards discovered that a good deal of treasure must have been carried away by the thieves and vagabonds of the town. A number of men were found carrying out of the gates something having the appearance of common logs of wood; and it was not suspected, until too late, that these logs were hollowed out, and filled with Sycee silver, a very ingenious contrivance to escape detection. A small quantity of treasure was found in one of the large buildings, supposed to be the office of the commandant, which was occupied by the sappers and miners. Most of the public offices were large and roomy buildings, affording good accommodation for a whole regiment of soldiers. The pile of buildings belonging to the admiral's department was assigned to the 18th and the staff, being within the walled town; while the 49th were quartered in the outer town, in a large building belonging to the office of the Intendant of Circuit. The 55th occupied an extensive range of buildings belonging to the Prefect of Amoy; the artillery retaining possession of a commanding position overlooking both the city and the outer town. Late in the day, and also on the following morning, Sir Henry Pottinger and Sir William Parker landed, to take a view of the town; but, after visiting the principal buildings, they returned on board ship. Numerous patrols were found necessary, by day and night, in order to preserve quiet in the public streets, and to check the boldness and rapacity of the swarms of Chinese thieves and rogues, who hovered about like a raging pestilence in every part of the city, and crowded in from the country the moment the respectable inhabitants left the town. The inhabitants themselves were, in many instances, afraid even to defend their own property, or to aid our troops in restoring order and regularity; they dreaded the probable imputation of having traitorously aided the foreigners, and the fear of extortion and punishment from their own authorities, at some future period,
  • 73. served to disorganize the whole community. In vain did Sir Hugh Gough appeal to the more respectable merchants and householders to aid him in protecting property; all that he could get from them was empty promises, of which they were very liberal, but from which no good result followed. Even within the citadel, or walled town, it was with the utmost difficulty that the daring thieves and vagabonds could be kept in check; and hardly could even a single Chinaman be induced to point out to the guards at the gate the real bonâ fide owners of houses or property, in order that they might be allowed free egress and ingress. The injury which the inhabitants of many Chinese towns suffered during our operations must not be estimated by the actual damage (generally trifling) done by our fire, or by the presence of our troops. In most instances, even before hostilities commenced, the presence of the Chinese troops, who were marched in probably from several distant provinces, became almost a scourge to the inhabitants; and afterwards, when a town was taken, and the local government disorganized, much greater damage was done to the property of the people by the low mob of plunderers, than would, under any circumstances, have been allowed by our own victorious soldiers; indeed, some instances occurred in which the former were shot by our guards, rather than desist from their evil doings. Our men often resisted temptations of no ordinary kind; houses were found abandoned, property left unprotected, shops open, and goods strewed about; and even the abominable spirit, samshu, (distilled from rice,) was sometimes almost purposely placed in their way. The instances of misconduct were few, even under these peculiar circumstances. Among other discoveries was one calculated to corroborate at first sight the notion of the prevalence of infanticide among the Chinese. In a large tank near a public building, by some supposed to have been an hospital, were found the dead bodies of several young infants which had been drowned, having been thrown in, sewn up in pieces of mat. But there was nothing to determine whether the
  • 74. horrid deed was done out of fear that violence might be offered to the women and children, or whether it was really an instance of the practice of infanticide, which has been said to prevail in China to a much greater extent than it really does. The former explanation may possibly in this instance, as in some later ones, be the true one. The interior of the island of Amoy was not occupied, or even examined, for it was feared by the general that the presence of our troops would so much alarm the respectable and influential inhabitants, that the whole place would be given up to the rapacity and lawlessness of the innumerable miscreants who watched for every opportunity of letting loose all their bad propensities; but the Nemesis, accompanied by the Algerine, and having in tow the launch and pinnace of the Blonde, was ordered to steam round the island, and search for war-junks. None, however, were found. The island of Kolingsoo appeared so completely to command the harbour and approach to Amoy, that the occupation of that position only was calculated to answer every good purpose, without the necessity for the retention of Amoy. It was the opinion of Sir Henry Pottinger, in which the general and the admiral perfectly coincided, that no measures should be taken for the permanent occupation of the city, and that a small garrison only should be left at Kolingsoo, while the remainder of the expedition should move further northward with the least possible delay. It was necessary, however, to wait a day or two for favourable winds, and measures were taken for the destruction of the numerous works which had been constructed upon the outer islands. The Nemesis was employed on this important service on the 30th and 31st. Having been joined by two launches and other boats, with a party of seamen and marines from the Wellesley, Blenheim, and Druid, under Commander Fletcher, she proceeded to destroy some forts and guns, principally on the south-west side of the bay, all of which had been abandoned by the Chinese. On this occasion, five forts or field-works and forty-two guns were taken possession of and destroyed, and on the following day several others of the same
  • 75. description were also disabled. A body of Chinese soldiers, who shewed themselves near a small fort on the island of Quemoy, at the eastern entrance of the bay, were dispersed, and several guns, matchlocks, ginjals, &c., together with a quantity of gunpowder, were destroyed. Altogether seventy-seven guns and four forts were destroyed in this day's work, and the admiral publicly spoke of the "very commendable zeal" which had been displayed. At Amoy, for the first time, the so-called tiger soldiers shewed themselves—that is, men dressed up in yellow-coloured clothes, with black spots or stripes upon them, and a covering for the head, intended to be a rude representation of a tiger's head, supposed to look very fierce, and to strike terror into the minds of the enemy. The island of Kolingsoo, which had been retained in our possession ever since its capture, deserves a few remarks. It is about a mile and a half in length, and about three quarters of a mile broad, but is very irregular in its shape. It principally consists of rocky broken ground, the greater part of which is barren, but interspersed with unwholesome rice-grounds, which have contributed to render the place extremely unhealthy; indeed at one period the mortality among the troops stationed there was dreadful, scarcely even a single officer having escaped sickness, which proved fatal to many. The Chinese, however, seemed to have suffered little from it, for there were several neat and even elegant country-houses upon the island, ornamented with handsome carved wood-work, &c. It seemed to have been used as a place of retirement for some of the wealthier citizens of Amoy, and our retention of a place so conveniently situated for giving us the command of the harbour and trade of the city was a source of great annoyance, both to the authorities and to the inhabitants. For a considerable time, very little communication was kept up with the town, and it was scarcely safe to venture into it; but since the peace, every disposition has been shewn to receive us in a friendly manner, and the knowledge which many of the Chinese merchants have acquired of our character and habits, by trading with
  • 76. Singapore, will tend materially to facilitate our future commercial intercourse. Several American missionaries have resided at Kolingsoo, and without doubt will, at no distant period, succeed in winning the attention and good-will of many of the inhabitants of Amoy. A boundless field has at length been opened for missionary enterprise in the benighted empire of China; for, although it cannot be said that the country has been made completely accessible to the foreigner, still the hostility of the government has been materially modified. It rests with the Christian nations to profit as Christians, by the opportunities which cannot fail to offer. Among a people so fond of reading and thinking, and so given to study and inquiry as the Chinese generally are, the best possible results are to be expected from the judicious teaching of Christianity, and, above all, of Christian practices. If China is really to be opened, it is to be effected by missionary enterprise cautiously and judiciously, and, above all, not too hastily applied. The most valuable of all aids to these undertakings, is that of medical knowledge, which may be considered as almost indispensable to the proper character of a missionary in China. The relief of bodily suffering (above all, in a country where the medical art is so low as it is in China) softens the feelings of our nature, and paves the way for kinder influences over the mind itself. It will open the family mansion of the most secluded and prejudiced Chinese, when words or doctrines first propounded would meet an unwilling or perhaps a hostile listener. Religious teaching and the practice of the healing art, the comfort of the suffering mind, and the solace of the tortured body, must go hand in hand in effecting the good work of "opening" China. Why is it that the Americans have taken precedence of the English in this great and glorious work, since the commencement of the war in particular? For many years, a talented medical missionary, Dr. Parker, has dispensed his double blessing upon the Chinese at Canton, and can testify the gratitude of the people, from the highest to the
  • 77. lowest, and the readiness with which they have accepted his counsel and his teaching in both capacities. At Macao, Hong-Kong, Kolingsoo, and Chusan, the Americans have alike preceded us. There is, however, one great and fatal error to be avoided; and that is, the rivalry of religious sects among each other, and the attempt to gain followers at the expense of each other's tenets. It was this want of unanimity which in some measure produced the decline of the influence of Roman-catholic missionaries in China. The garrison which was left by Sir Hugh Gough upon the island of Kolingsoo consisted of three companies of the 26th regiment, with a wing of the 18th, and a small detachment of artillery, comprising altogether about five hundred and fifty men; the whole under the command of Major Johnstone, of the 26th; and the Druid, with the Pylades and Algerine, were also to remain there, under the command of Captain Smith, C.B., as a further support, to ensure the complete command of the harbour of Amoy. The number of troops employed during the operations against Amoy was as follows:—
  • 78. Officers. Men. Artillery, European and Native, Captain Knowles 9 240 18th Regiment Royal Irish, Lieutenant Colonel Adams 30 648 26th Regiment (Cameronians), Major Johnstone 8 153 49th Regiment, Lieutenant-Colonel Morris 24 460 55th Regiment, Lieutenant-Colonel Craigie 26 731 Madras Sappers and Miners 6 184 ———— Total 103 2416 Four native officers, and serjeants and drummers, are included in the second column.[56] In the afternoon of the 4th of September, the weather having become calm and fine, the preconcerted signal for the embarkation of the troops from the town and island of Amoy was made on board the flag-ship. Upon this sudden order, the troops were paraded in perfect regularity, without a single instance of drunkenness or misconduct, after eight days of harassing duty on shore, amid temptations of every kind. Under the direction of Commander Giffard, of the Cruiser, the whole force was embarked without any accident, by half-past six o'clock, on board the Nemesis and other steamers, which conveyed them out to their respective transports, in readiness to sail on the following day. Not even a camp-follower was left behind (and they are generally a very troublesome class); but, in order to make sure that there was no straggler, the Nemesis was afterwards sent in again to the town to bring off any one that might accidentally have been left. But the only straggler which was found, happened to be a fine fat bullock, which was soon put on board the Nemesis and carried off. Every preparation was now completed for the departure of our forces on the following morning, the 5th of September. FOOTNOTE: [56] List of H.M. ships and vessels, and of the Honourable Company's steam-vessels, in action at Amoy, 26th of August, 1841. Wellesley (flag) 72 Captain T. Maitland. Blenheim 72 Captain T. Herbert. Blonde 44 Captain T. Bourchier. Druid 44 Captain H. Smith. Modeste 18 Captain H. Eyres. Cruiser 16 Commander Giffard. Pylades 18 Commander Anson. Columbine 16 Commander Clarke. Bentinck 10 Lieutenant R. Collinson. Algerine 10 Lieutenant T. Mason. Sesostris steamer 4 Commander Ormsby, I.N. Phlegethon steamer 4 Lieutenant M'Cleverty, R.N. Nemesis steamer 4 Mr. W. H. Hall, R.N. Queen steamer 4 Mr. W. Warden, R.N.
  • 79. CHAPTER XXVII. All those persons who have visited Amoy, either out of curiosity or on matters of business, appear to agree with each other in regarding it as a place peculiarly adapted for the extension of European trade. The mercantile spirit and enterprise of its inhabitants, and their anxious desire to trade with foreigners, when not held back by the arbitrary orders of the mandarins, have been long known and recorded by several travellers, before there was any prospect whatever of the trade being opened. Mr. Gutzlaff observed respecting it, in the account of his voyage along the coast—"Its excellent harbour has made it from time immemorial one of the greatest emporiums of the empire, and one of the most important markets of Asia. Vessels can sail close up to the houses, load and unload with the greatest facility, have shelter from all winds, and in entering or leaving the port, experience no danger of getting ashore. The whole adjacent country being sterile, the inhabitants were forced to seek some means of subsistence elsewhere. Endowed with an enterprising spirit, and unwearied in the pursuit of gain, they visited all parts of the Chinese empire, gradually became bold sailors, and settled as merchants all along the coast. Thus they colonized Formosa, which, from that period to this, has been their granary, and visited and settled in the Indian archipelago, Cochin China, and Siam. A population constantly overflowing, demanded constant resources for their subsistence, and this they found in colonization; and thus they spread themselves all along the coast of China, up to Mantchou Tartary. As soon as the colonists amass sufficient money, they return home, which they leave again when all is spent." Elsewhere he says, "Many of these merchants, settled in the northern parts of China, return annually with their profits. It is not surprising, therefore, that a large amount of Chinese shipping belongs to Amoy merchants, and that the greater part of the capital employed in the coasting trade is their property. Hence, even this barren tract is become one of the richest in China, from the enterprise of its inhabitants. Wherever the people go they are rarely found in a state of abject poverty; on the contrary, they are often wealthy, and command the trade of whole islands and provinces, as well by their capital as by their superior enterprise and industry." The English, who had formerly a factory at Amoy, were compelled to relinquish the trade by the severe extortions to which they were subject. The Dutch continued it for a longer time, but neglected it when their influence at Formosa ceased. The natives of Amoy have always shewn themselves ready to cultivate the friendship of foreigners, wherever they have been, and in their dealings they have a character for honesty beyond all other Chinese. They are more ambitious of successful mercantile enterprise than of literary distinction or advancement, which is generally so dear to a Chinaman. The shops of Amoy are generally well supplied with the necessaries and luxuries of life, the merchants are civil, and although the town is neither handsome nor very cleanly, and the population in some parts of it are densely crowded together, still there are many fine houses, which indicate the possession of wealth and consequence. An immense trade is carried on between Amoy and the island of Formosa, to which a great number of emigrants are even still attracted from the province of Fokien. Before the occupation of Hong- Kong was thought of, several proposals were made for forming a British settlement upon Formosa, as being conveniently situated for extending our trade with the inhabitants, not only of the adjacent district of Fokien, but of the whole coast of China. This suggestion was partly encouraged by the recollection of the settlement which the Dutch once possessed upon the island; but it seemed to be forgotten that the Dutch were at length forcibly expelled, and that the population having greatly increased since that period, it is not likely that we should be suffered to retain possession of any part of the island without being constantly harassed and provoked to bloodshed; moreover, the privilege
  • 80. of trading with Amoy does away with all probability of advantage to be derived by direct trade with Formosa. Among other proposals, that of a settlement upon the Bonin islands (which are said already to belong to Great Britain) was suggested, with a view to commercial enterprise with China; and Mr. Tradescant Lay warmly supported this notion. These islands were taken possession of by Captain Beechey, of H.M.S. Blossom, in 1827, and they extend from latitude 27°, 44', to 26°, 30' N., being about five days' sail from the Lew-Chew islands, and three from Japan. In the course of a few years, it is not improbable that Port St. George, the principal harbour, may be resorted to, with the object of pushing our trade even into Japan itself. At the present moment, indeed, several Englishmen and other Europeans are settled there, and are principally concerned in the whale fishery. There are also a good many natives of the Sandwich Islands at Port St. George. The islands are volcanic, but are rendered productive with moderate cultivation. It is worth while here to mention that the Bonin Islands and the Sandwich Islands lie directly in the line of future intercourse between China and the west coast of America, and that it has been thought not improbable that a new route to China may some day be opened, by way of California and the islands above-named. To return from this digression to the island of Formosa, which has claimed our particular interest since the massacre of so many of our shipwrecked countrymen by the authorities, shortly before the termination of the late war. In this horrible tragedy no less than two hundred and eighty-three human beings were put to death in cold blood, without any other crime than that of helplessness, and without any other object than that of obtaining rewards by fabricated statements, and honours by false pretences. Formosa was the last conquest of the present Tartar dynasty, and even since it has been brought under Chinese dominion, the rebellions and disturbances of its unruly inhabitants have been a frequent source of alarm to the government. The imperial troops have been frequently defeated with great slaughter, and peace is said to have been purchased by bribes more frequently than it has been won by conquest. The aboriginal inhabitants are still numerous in the mountain districts, and along some parts of the eastern shores, but they, are said to be much oppressed by the Chinese colonists, and also by the authorities. When the Tartars first began the conquest of China, great numbers of discontented spirits went over to Formosa from the neighbouring provinces, and it has been recorded that one hundred thousand people took refuge there. The island belongs to the province of Fokien, along which it is situated at a distance varying from seventy to one hundred and twenty miles, the passage between it and the mainland being called the Formosa Channel. The length of this island is about two hundred and twenty miles, but the breadth of it is extremely irregular. The Chinese population is at present supposed to amount to about two millions, and is constantly on the increase, by the accession of an influx of emigrants from the mainland adjoining. They are attracted thither by the fertility of the soil, and the great facilities for cultivating sugar and rice, which are there grown to an extent sufficient to supply a vast quantity of these necessary articles to the inhabitants of the mainland, and to employ several hundred trading junks in the traffic. It is worthy of remark, that the Dutch contrived to establish themselves upon the island of Formosa, and ultimately to form a factory there, before the Tartar conquest, and before it was regularly colonized by the Chinese. The Japanese also partly contributed, though in small numbers, to colonize the island. The Dutch had a small garrison at a place called Tanshuy, or Tamsui, at the northern extremity of the island, and another at Kelung, not very for from it. Their object was to make use of their settlement as a depôt, or centre of trade, from which their operations could be extended along the coast of China and Japan. Their influence was, however, of very short continuance, as they were ultimately completely driven out of the island, after some few struggles, by the famous pirate, Coxinga, in 1662, about thirty or forty years after they had fairly established themselves on it.
  • 81. The present capital of the island is built upon the site of the principal Dutch factory of former times, and is called Ty-wan-foo; it is upon the west coast, some distance down towards its southern end. The harbour has, however, become almost inaccessible, except to vessels of very light draught of water, owing to the accumulation of sand, which is thought to frequently change its place. Indeed, the sea has gradually continued to retire from many parts of the coast, and harbours which were once frequented are at present inaccessible. From the time of the expulsion of the Dutch, to the period of our operations upon the coast of China, little seems to have been known or heard of Formosa; and, owing to the jealousy of the Chinese, and other causes, no attempt seems to have been made to explore the island. The colonists are described as being generally very turbulent and given to violence, as it has become a place of refuge for all the bad characters who can manage to escape from the mainland; but it is also the home of many respectable and enterprising settlers; although, being removed from the control of the superior officers of the province, they live with less restraint, and therefore readily become bold and lawless. For the same reason, the local mandarins are cruel, rapacious, and ignorant; and their behaviour towards our unfortunate countrymen will suffice to stamp them with the character of treachery and thorough baseness. But the cultivation and prosperity of the island have increased in a rapid and remarkable manner; and it is evident that British manufactures will soon be spread among its numerous population, through their intimate connexion with Amoy. Besides furnishing immense supplies of rice, Formosa also produces great quantities of sugar, camphor, and tobacco, which are exported to Amoy. A great part of the camphor is already carried down to Singapore in the trading junks from Amoy, but probably our own trading vessels will henceforth procure supplies of it on the spot, in exchange for cotton and other manufactured articles. Unruly as the people of Formosa are, the island is, nevertheless, somewhat famous for its schools, which are said to be in a flourishing condition. Mr. Gutzlaff states, that the rich men of Fokien frequently send their sons over to obtain literary degrees at Formosa; and the Dutch, at an early period, took pains to spread Christianity among the inhabitants, who, at that time, were comparatively few in number. A few books on Christianity were translated by them into the Formosan language, and they were very successful in making converts. Since they abandoned the island, however, nearly all traces of their early labours have disappeared. The close connexion of Formosa with Amoy will probably be the means of reviving amongst the inhabitants some of the lost spirit of Christianity; for we cannot doubt that, in all parts of China, the increase of missionary labour will keep pace with the increase of commercial intercourse. The wreck of the Nerbudda transport, on her way up to join the expedition with camp-followers, in the month of September, 1841, soon after our forces left Amoy, and the loss of the brig Ann, a trading vessel, on her way down to Macao, from Chusan, in the month of March following, upon the shores of Formosa, served to attract unusual attention towards that island, and to put us in possession of some little information respecting the interior. The history and ultimate fate of our shipwrecked countrymen is calculated to awaken the most painful interest. On board the Nerbudda there were altogether two hundred and seventy-four people; of whom, twenty-nine were Europeans, two natives of Manilla, and two hundred and forty- three natives of India. The captain and the rest of the Europeans, with the two Manilla men, and only three Indians, got away in the ship's boats immediately after she struck, and were providentially picked up some days afterwards by a trading schooner, called the Black Swan, on her way down to Hong-Kong. The unfortunate Indians, to the number of two hundred and forty, who were left upon the wreck, after remaining by her for five days, managed to construct rafts, upon which they attempted to reach the shore. Many of them, however, perished in the surf, and others are supposed to have been murdered by the Chinese plunderers. The exact number, therefore, who fell into the hands of the Chinese authorities, and were imprisoned and subjected to the greatest privations,
  • 82. cannot be ascertained; but they were thought to amount, according to the best information which could be obtained, to more than a hundred and fifty. On board the brig Ann there were in all fifty-seven souls; of whom, fourteen were natives of Europe or America, four Portuguese, five Chinamen, and thirty-four natives of India. Out of all those who were taken prisoners, belonging to both vessels, only nine ultimately escaped an untimely fate, and were restored at the end of the war, according to the terms of the treaty. The following account of what befel the unfortunate sufferers on board the Ann will apply, with little variation, to those who were wrecked before them, in the Nerbudda. It is extracted and condensed from a curious journal, kept by one of the sufferers, a fine young man, who was a passenger on board. It was found concealed in his cell, after his unfortunate fate, and cannot but awaken feelings of deep commiseration for all his companions in distress.[57] It was written upon common Chinese paper, with a piece of bamboo, and the account was continued to within five or six days of the time when the final tragedy is supposed to have taken place. It was written day by day, as the various little occurrences took place, and some of the observations casually made upon the appearance of the island will be read with great interest; but I have thought proper to omit the minutiæ and repetition of abrupt and hasty notes, which would have been tedious and of little benefit. It will here be proper to mention, that prompt redress and "condign" punishment upon the heads of those high officers, whose false and pitiless misrepresentations occasioned the final catastrophe, has since been demanded, in firm and dignified terms, by her Majesty's plenipotentiary; and one of the conditions insisted on was, "that the property of the high authorities of the island, who were perfidiously concerned in the affair, should be confiscated, and the amount paid over to the officers of the British government, to be applied to the relief and support of the families of the innocent men who suffered." By the orders of the Emperor, a strict investigation has been made into all the circumstances connected with the dreadful event; and a report has been sent up to Pekin, by the Viceroy of Fokien, condemnatory of the misrepresentation and duplicity of the authorities of Formosa. The whole of the fifty-seven individuals who were on board the Ann quitted the wreck at daylight; and, having marched along the shore about two miles, they fell in with two junks, lying wind-bound in a small river or creek. They hoped to be able to put to sea, and stretch across to Amoy; but the gale continued so violent that it prevented them from getting out of the creek. They were not ill- treated by the Chinese junkmen, but, as they were without food of any kind, and exposed to a cold, cutting wind, it was soon evident that they must surrender themselves to the Chinese authorities. Soldiers soon gathered round them in crowds; and, as they had very little ammunition, any attempt to defend themselves, which might have caused the death of some of the soldiers, or of the mob, would certainly have been followed by the massacre of the whole party. In the afternoon, they all gave themselves up, without having fired a single shot, and without attempting to make any kind of resistance. They were immediately stripped and marched away, exposed to the most cutting wind and sleet, without any covering, their feet cut by the sharp shells with which the beach was covered, and with very little allowance of food. It is not surprising, therefore, that two men soon died from fatigue and exposure, and several others fell from sheer exhaustion, and were obliged to be carried along in baskets; others were afterwards carried in sedans, more for sake of security than from any feeling of compassion for them. It was remarked, that during the whole journey of thirteen or fourteen days, to the capital of the island, the lascars or Indian sailors shewed a great deal of bad and selfish behaviour towards each other. Each man of the party had a ticket fastened round his neck, stating what he was, and whence he was brought; being treated in this respect like public criminals. For a great length of time their food was only salt fish and greens, with sometimes rice. They suffered all sorts of abuse and indignities in every town and village through which they passed; but it is remarked, "that the women (who did not appear to be at all secluded) did not join in this, although they exhibited the usual curiosity of the sex." They were observed throughout the whole
  • 83. journey to be very plain, but they had a pretty fashion of dressing their hair, by weaving natural flowers amongst it.[58] After the first two or three days, they came to a considerable walled town, where they were placed for the night in two cells, about eight feet by seven feet, in which twenty-five unfortunate beings were stowed, with nothing to lie upon, the weather being intensely cold. Three guards were placed over them. The rest of the party were taken by a different route, but they all ultimately reached the capital. One large town they came to was enclosed, as were some others, by a high, red brick wall. It was situated in a large paddy swamp or valley, interspersed here and there with small hamlets, around which the bamboo plantations were growing in great beauty and luxuriance, and of extraordinary height, many of them measuring upwards of sixty feet. In some of the smaller towns and villages, the so-called gates (for they all had them) were constructed of bamboo. The country appeared well cultivated in many parts, and wheat and sugar-cane were met with; but other parts of the country were very barren, and covered with large stones, such as are called "boulders," in some parts of England. Generally, the men were made to wear handcuffs, but they were not of great strength, for some of the party managed to break them off; and they were then carried along in chairs, under a strong guard of soldiers, but were occasionally allowed to walk. Wherever they went, the crowd and annoyance of the hosts of curious gazers, who frequently insulted them, was so great that it was a relief to get lodged in the common gaol, which was divided into several cells, each cell having cages in it, made of wooden bars, just like the dens of wild beasts. The cells were also provided with a regular pair of stocks, in order to afford greater security, if required. One of the cells was filled with Chinese prisoners. The great object of the mandarins now appeared to be, to get some of the party to admit that the Ann was a man-of-war, sent to look after the crew of the Nerbudda, who were known to be still upon the island. With this view, two of the men were mercilessly beaten, but without the desired effect. So common and so public a practice did opium-smoking appear to be, that even the soldiers who acted as an escort carried their opium-pipes in their girdles. For the first twelve days, the prisoners were never allowed to wash even their faces, and at length they could only do it in a dirty pool by the road side. For the last four days before they reached the capital, called Ty-wan-foo, they were compelled to wear leg-irons as well as handcuffs. Generally, they were allowed to purchase their own food during the journey; for which purpose a little money was given to them, at the rate of one mace, or about fivepence, a day. But this was only after the first few days. It was remarked that wheel-carts were in common use in the island, and tracks of them were seen in all directions. On the mainland of China these are unknown, except in the neighbourhood of Pekin; but, in the island of Hainan, to the southward of Canton, they are very common, and similar in construction to those in use upon Formosa. They are, however, very clumsy and inconvenient; the wheels, which are small, being composed of two semicircular pieces of solid wood, joined together, with the axle fixed into the wheel itself, so as to revolve with it, and not within it, but made to turn round under the body of the cart. The roads or causeways are generally broader than upon the mainland, and were in many places shaded with bamboos on each side. Several rivers were crossed near the capital, and the country was somewhat improved in appearance. About twenty miles from Ty-wan-foo they passed a night in a large town, with walls built of chunam; at the entrance of which were placed several very long guns, not mounted on carriages, but fixed upon the ground, rather to indicate their good intentions than their ability to perform them. Here again they were lodged in the common gaol; and, on the following morning, the Chinese servant who had been taken prisoner with them had a chain put round his neck, in addition to his leg-irons and handcuffs. The next night (the last before they entered the capital) was spent at an inn by the road-side, which was so crowded with travellers that scarcely any food could be procured. The Chinese had regular fights and scrambles for the little which was to be had, and their appetites appeared by no means delicate; but, whether their hunger was appeased or not, they were all prepared in the evening to enjoy in good earnest the luxury of the opium-pipe, soldiers and
  • 84. travellers all alike; nor did the two mandarins who were present interfere in any manner to point out its impropriety. On the 24th March, (fourteenth day since the wreck,) they were destined to make their wretched entrance into the capital. At the distance of six or seven miles from it, they were met by an officer and a few soldiers, by whom their names and their numbers were called over, according to a list which the officer held in his hand, and they were then separated into smaller parties, and led by different routes into the city. As they approached the gate, they, for the first time, caught a glimpse of the sea, with a few junks at anchor at a distance, towards which they hopelessly strained their longing eyes. The walls of the city appeared to be in a state of dilapidation, except near the gateway, where they had been recently repaired and whitewashed. The prisoners were now fairly within the capital of Formosa, and were conducted to an open space, planted thickly with trees, but broken up by rough watercourses, over which there were several bridges of stone. Thence they were led through back lanes, avoiding the principal streets, to the house of a high mandarin, in front of which they halted for a short time; and such was the pressure of the crowd and the curiosity of the people, that the chairs in which they had been brought were nearly pulled to pieces before they were ordered to get out and enter the outer gateway of the mandarin's house. Here they were drawn up in line, to have the tickets round their necks copied; but before the process could be half finished, the pressure of the crowd became so great that the mandarins were obliged to discontinue the task. A ludicrous scene followed, which, for the moment, afforded amusement even to the prisoners themselves. The enraged mandarins charged the mob in great fury, and whipped them with their long tails, which, having silk woven on to the ends, gave some tolerable cuts to the people's faces. For a few minutes our hapless prisoners were put for refuge into a small temple which was close at hand; but even here the mob pressed so hard upon them that the door was nearly smashed in; and, as a last resource, they were marched off, with heavy irons on their legs, which bruised them at every step, to a prison in the courtyard of a superior mandarin's house, about one hundred yards distant. Here their treatment was very bad; for several successive days they were brought up before the mandarin to answer an infinity of questions, many of them very puerile, about the names, ages, and duties of every one on board the Ann; also about geography and the possessions of Great Britain, and where the poppy was grown; how money was raised, &c. &c. The Chinese carpenter of the vessel acted as interpreter; and, on one occasion, both he and the other Chinaman were severely flogged with bamboos. After some time, those who could draw were allowed to sketch ships, carriages, and other things, which exceedingly amused the Chinese, who were glad to purchase them; so that by these means they were able to procure food and tobacco, and thus to diminish in some degree their chances of being carried off by starvation or sickness. After the lapse of a week or two, fever broke out, and they were then separated into smaller parties, and put into different cells or prisons, some faring better, some worse, according to the temper or caprice, or even roguery, of the particular jailer who chanced to have charge of them. One of these wretches seems to have been a perfect fiend of his class; he kept one party of ten miserable human beings in a den so small that not one of them could lie down at night. It will scarcely be believed that they were made to exist for two whole months in this horrid black hole, only eleven feet six inches long, by seven feet six inches wide; grudging each other every little inch of room, and longing even for the little bit of space which the single insensible bucket, which was the only piece of furniture, occupied in their den. Here were ten human beings stowed away together, some sick, some sore, and all in pain and misery. For some time they were not permitted to come out of the den at all, but at last they were let out once a day, and were allowed a very little water to wash themselves; only two or three, however, could wash themselves on the same day, so that the whole of them could only be able to wash themselves once in three days. Of course, they were dreadfully infected with vermin of every kind, and, as the author of the journal expresses it, "A few weeks have
  • 85. sufficed to bring me down from a strong hale man, to a wretched helpless being, disgusted with myself." Many attempts were made to get a note sent across to Amoy, to give information of their situation; and the promise of one hundred dollars on its safe delivery, and one hundred more on bringing an answer back, (to be paid at Amoy,) sufficed to induce a tolerable trusty Chinaman to undertake the task. We shall see presently how far it succeeded. It has before been stated that the several parties fared differently, according to the humanity or rapacity of the particular jailer. Something also depended upon the particular mandarin under whose supervision they were placed, but it is noticed that the highest, or red-button mandarin, was the best of all, and frequently ordered some of the hardships they complained of to be remedied, particularly as regarded the quality of the food. On the other hand, it is stated, that one of the jailers, who was humane enough to allow his party of prisoners to be shaved, was taken before a mandarin and punished with fifty strokes of the bamboo; after which, no visitors were allowed to see them at all, and the jailer became very sulky, except when he was drunk, which he generally was, by the use of opium, every evening. Sometimes they were taken out of prison in order to draw for the mandarins, at others, to undergo repeated examinations for their amusement. In the first instance, however, the object invariably was, to betray them into an admission, however remote, that the vessel was really a man-of-war. But it was quite evident that they knew perfectly well that she was not so, and at length the red-button mandarin put an end to this part of the business. From this time, their questions were more of a general nature, but many of them were exceedingly absurd. The mention of Sir Henry Pottinger's name (for they appeared already to have heard of him) invariably made them angry, and on one occasion they inquired whether he was a white or a black man. They also inquired a good deal about the Queen, her court, and ministers, mode of life, &c., and how many husbands she was allowed to have; expressing great astonishment when they learned that in Europe kings and queens, as well as private individuals, had only one wife or husband; and then they proceeded to enumerate the virtues of their own emperor, and to plume themselves upon their own cleverness. On one occasion, they asked whether America had not, some time or other, been situated in England? whether a man could now walk from London to America in a week? how large London was, and how many outside (foreign) nations are subject or tributary to England? Endless were their curious questions, and on one occasion they exhibited an officer's jacket, and a corporal's coat with the 55th button on it, and particularly inquired the use of an epaulette, which they held up, fancying it was intended to be worn on the head. During the first half of the month of May, it rained incessantly, and they were very imperfectly protected from its effects. In fact, the rain always beat through their roof, and when it was heavy, or long continued, it flooded their den: the least bit of dry plank, or a partially sheltered corner, was matter of envy and contention; and, as may be supposed, they not only suffered from bad food, confinement, vermin, and ill-health, but were incessantly tormented with the most venomous mosquitoes, producing inflammation and sores. In this condition they were kept in the most harassing state of suspense; one day being assured that they would be sent away in a month; another, that they had no chance of liberty for six months; and the very next, perhaps, that their heads would soon be taken off. Fortunately, the talent for drawing possessed by Mr. Gully and Captain Denham, served to gain for them friends and pacify enemies. In this way, month after month continued to drag its slow length along. At the end of about three months' close confinement, a slight change for the better took place; they were moved into rather better quarters, where they were only three together, so that they had more room to breathe; they were also allowed water to wash themselves, and a little money was given to them. It was thought that this arose in consequence of information received by the authorities that there was some chance of an attack being made upon this island, by our forces at Amoy, with a view to liberate the
  • 86. prisoners. It was now ascertained, also, that the fisherman who had promised to carry over the letter to Amoy, two months before, had succeeded in his attempt, and an answer had been brought back by him, which held out the prospect of speedy release. Another letter was also sent off to Amoy; so that now at length their hopes again revived. But sickness had already begun its work, and their minds were so depressed that even the boldest, who tried to bear up bravely to the last, recorded his feelings that "One miserable day passed after another, with nothing to help them to break in upon the wretchedness of their existence; no exercise being permitted, and nothing, in fact, to relieve the dreadful monotony of such prison life." And what was the little improvement in their lot, which resulted from their removal into other cells? "We now, (three of us,") said he, "have five planks with a mat upon them to sleep on, and glad we are to get into this new place, which is the Executioners Den, and which, until we had ourselves cleaned it, could never have been cleaned since it was built." On other occasions it is noted, "we scalded our clothes this morning, to kill the vermin." It was thought that the day they were removed into this new berth must have been the Emperor's birthday, or some day of rejoicing, for they had at the same time a dinner of roast pork, with sweet cakes, and each man received one mace, or fivepence in money. But this was too good to last—a mere freak of fortune! Generally speaking, their food was so bad, that a great part of it was thrown away, and it was only by quarrelling with the jailers, and threatening to complain to the high mandarin, that they could succeed in procuring any eatable food at all. In the month of June, several shocks of an earthquake were felt, followed by terrific storms of thunder and lightning. It is due to the better class of mandarins to remark, that when complaints were made to them, they procured some temporary improvement for the prisoners. On the 4th of July, it was made known that honours and rewards had been largely conferred upon the mandarins, for having contrived to make so many prisoners. This was in answer to their false accounts of the business to the Emperor, in which they said that they had attacked and destroyed two English men-of-war which came prying into the coast, and had taken all the people prisoners, enumerating the number of black, and red, and white barbarians, and the quantity of barbarian guns. On the 10th of July, Mr. Gully, who had necessarily been ailing for some time, became seriously ill with dysentery, brought on in a great measure by eating large quantities of mangoes. The Chinese recommended him two cures for it; one was, to eat the skins of the mangoes alone; the other, to eat opium. The former he found to have a good effect, at least so far that his complaint improved under the treatment; the latter he was able to purchase at a moderate price from the visitors, who brought it on purpose for him; it was different from the extract which is used for smoking, and apparently much less powerful. The same mandarin who had given them a treat upon the Emperor's birthday all along shewed more interest in their condition than any of the others; and one day, in the hope of inducing him to give them some kind of indulgence, they told him that it was the birthday of the Queen of England's eldest child, and that they all entertained so strong a feeling of "filial obedience" and affection towards their queen, that they wished to celebrate the event. To their great surprise and delight, the mandarin's heart was moved by this appeal, and he gave each of them money; to some five mace, to others three, (equal to about two shillings,) and then sent them a good dinner, and made himself quite agreeable; and, of course, all the inferior officers, including the jailers, took their tone for the day from their superior. On another occasion, the lascars were all brought up before the chief mandarin, having had new clothes first given to them, and he himself then presented each of them with a fan! All these circumstances naturally tended to revive their hopes, and little did they dream of the horrible catastrophe which was soon to take place. Towards the end of July they were informed, that in the course of half a moon more an answer would be received from Pekin, containing the Emperor's commands as to what was to be done with the prisoners; and they were warned that, if
  • 87. his majesty ordered that they should be decapitated, it would immediately be carried into effect. From this it would seem that the authorities fully anticipated that the representations which they had made would induce the Emperor to issue such a cruel command; but the prisoners themselves still retained sufficient hope to induce them to disbelieve the probability of such a tragedy. With the exception of Captain Denham (whose life was saved) and the Chinese carpenter, it does not appear that any of them were tortured; but the dreadful cries of some of the Chinese prisoners could be distinctly heard; and two poor fellows were seen passing by with their hands blackened, having been condemned to have them chopped off. One remark is worth recording—namely, that the mandarins, from the highest to the lowest, as well as all their servants and attendants, were in the constant habit of smoking opium. Tobacco was also in general use, as elsewhere in China, and was extensively cultivated on the island. There was also noticed (what should have been mentioned before) a curious vine-like plant, grown upon trellis- work, and frequently observed to be carefully covered up with mats; what it was no one knew, but more care and attention seemed to be bestowed upon it than upon anything else which was seen upon the island. The final tragedy is believed to have taken place upon the 12th or 13th of August, and is too horrible to dwell upon. They were beheaded with the sword. It is difficult to account for their having reserved nine individuals from the general massacre. Of these, six were Europeans or Americans, and three natives of India. It is supposed that they were retained in order to be sent to Pekin, to be there cut in pieces. Fortunately, the treaty of peace saved their lives, and they were at length conveyed to Amoy, and there met with all the attention they so much needed from their own countrymen. FOOTNOTES: [57] The information in the text was extracted from the manuscript, more than a year ago, in China. But the journals of Mr. Gully and Captain Denham have been recently published in full, in this country. [58] Probably the women at Formosa are much less numerous, compared with the men, than in most other places. The men come over from the mainland, but do not bring their women. It is believed that infanticide of female children is very prevalent at Amoy. The men are driven by poverty to emigrate, and have no means of providing for female children, who are therefore frequently smothered or drowned.
  • 88. CHAPTER XXVIII. On leaving the bay of Amoy, on the 5th of September, the appointed places for the rendezvous of the fleet of men-of-war and transports, in case of separation, were successively the so-called Buffalo's Nose, at the entrance of the Chusan group; Keeto Point, a promontory running out from the mainland towards Chusan; and, lastly, the bay or harbour of Tinghai, the capital of Chusan. The progress of the squadron was slow for some days, owing to light winds and a heavy swell; and the Nemesis, being very light in the water, and having, moreover, a leak in her bottom, (after the accident at Amoy,) was kept pretty close in shore, to avoid the swell outside, but seldom entirely lost sight of the fleet. A considerable quantity of floating wood was picked up alongshore, which was very acceptable for fuel, of which she had only a very small supply remaining on board. On the 13th, eight days after leaving Amoy, the north-east monsoon set in rather suddenly, and somewhat earlier than usual, with heavy squalls and a thick fog, which caused the unavoidable separation of the squadron. At the commencement of this change of weather, the Nemesis lost her fore-top-mast and top-gallant-mast, but continued her course leisurely alongshore until the following day, when she came to anchor under a small island at the mouth of the river Taitchou, about thirty- five miles from Sheipoo, and between fifty and sixty from the Buffalo's Nose. On the 16th, Capt. Hall landed upon the island above mentioned, under which he had taken shelter, with a party of men, to look for wood, which was much needed for fuel, and also for refreshments for the crew, and then took the opportunity of ascending a high hill, to take a survey of the neighbouring country. The haze cleared off sufficiently to enable him to discover the entrance to an extensive harbour, which proved to be that of Sheipoo, where there is a considerable trading town. He thought that he could also make out something like the appearance of batteries or field-works at the entrance. The Nemesis now stood in for the entrance of the harbour, which was very narrow, but fortunately, she soon fell in with a fishing-boat, in which were several fishermen busy about their nets, one of whom was made to come on board and pilot the vessel into the harbour; and he was promised ten dollars for his services if he took her in without any accident; but, if she touched ground, he was threatened to be immediately run up to the yard-arm. The poor fellow had never even seen a steamer or devil-ship before, and was not a little alarmed. But he perfectly understood the conditions, and gradually recovered his self-possession. The tide swept so rapidly into the narrow entrance of the harbour, that the Nemesis was fairly carried through the passage before the two small field-works, which were intended to protect it, could bring a single gun to bear upon the vessel; but the Chinese were seen running down from their little encampment above, to man the guns. At the bottom of the harbour or basin, the town now came into full view, with a large number of trading-junks of every kind, moored in lines close to each other on one side of the town; while on the other, or the left, as you looked towards it, there was a small fort, which appeared to have been recently repaired and strengthened, but, like most other Chinese forts, was left almost unprotected in the rear. Upon a rising ground behind the fort, a small body of troops, about five or six hundred in number, were drawn up, so that the Chinese were evidently prepared for defence. The Nemesis immediately ran in towards the fort, and took up a flanking position, anchoring by the stern between it and the town, so as to bring her guns to bear with the greatest advantage, without exposing herself to the direct fire of the fort. Shot, shell, and canister, were now poured in, and the fort was soon silenced. But the troops could now be seen descending from the hill behind, and bringing heavy ginjals with
  • 89. them, mounted on triangular stands, as if they intended to oppose a landing. However, a few discharges of grape-shot threw them into great disorder, killing many of them; Capt. Hall then landed, at the head of all the men who could be spared from the ship, accompanied by Mr. Gully, and took possession of the fort, the Chinese flying before them; four guns, two brass and two iron ones, were destroyed in the fort, the temporary sheds and buildings were set on fire, and water was poured into the magazine to destroy the powder. The whole party having now returned on board, boats were sent out, manned and armed, to search for fuel, and also to attempt to capture three large war-junks, which had been seen on the way up the harbour. All the trading-junks were left unmolested; but wood for fuel was so much needed on board, that several of the wood-junks were soon picked out, well filled with the necessary article. The opportunity was extremely fortunate, and in a short time, no less than seven boat-loads of excellent wood were obtained, amounting in all to about seventy tons. Much labour was required to bring off so large a quantity, and to stow it away expeditiously; nevertheless, during this operation, one of the war-junks was captured, (the crew having deserted her,) and, as soon as she was towed clear of the town and shipping, so as not to cause any unnecessary damage, she was set on fire in the middle of the harbour, and shortly blew up. Two guns, together with a quantity of ginjals, matchlocks, swords, &c., were destroyed in her. But the day's work was not finished yet. About two o'clock the cutters were sent away, manned and armed, under Mr. Galbraith, to destroy the other two war-junks which had been seen in the morning. One of them blew up close in shore, but the other was towed out into the middle of the harbour, before she was set on fire. One was found to mount fourteen guns, and contained a large quantity of powder, with numerous warlike implements of various kinds. The whole of this day's work was exceedingly interesting. The hills which surrounded the harbour were covered with people, who crowded out of the town, and from all the neighbouring villages, to witness the exploits of the "devil-ship," the rapidity of whose movements, the precision of her fire, and the volumes of smoke and steam which issued from her, seemed to awaken feelings of awe and mute astonishment, even more than fear. There they stood for hours, apparently unconcerned spectators of passing events; and as they saw the destruction of the war-junks, while the merchant- junks remained uninjured, they appeared satisfied that no mischief was threatened against the unarmed inhabitants so long as they did not interfere. The neighbourhood of the town along the shore was laid out in very neatly cultivated gardens, and everything bore indications of a thriving and well-ordered community. The day was now far advanced, and it only remained to capture the two forts or field-works upon the island, just within the mouth of the harbour. A shot or two had previously been fired at them in the course of the morning, but it was now determined to take possession of them, and destroy the works. On nearing them, a few shells and rockets were discharged into them, and the boats then put off, manned and armed, under Capt. Hall. The Chinese had only just abandoned them. The two field-works were very near each other, and were found to mount nine guns, which were spiked, their carriages destroyed, and the tents of the soldiers were set on fire. The poor Chinese fisherman who had acted as pilot was of course liberated as soon as the harbour was cleared, and he appeared no less astonished than overjoyed when the promised ten dollars were counted out into his hands. On the following day, the 18th, the Nemesis reached the appointed rendezvous at Buffalo's Nose, and found the Sesostris was the only vessel which had preceded her, the rest of the fleet having been kept back by contrary winds and hazy weather. When we remember what a large number of hired transports and store-ships passed up and down along the coast of China from this time to the close of the war, many of which had frequently a great part of their crew sick, we cannot but be surprised[59] that so few accidents happened. The inaccuracy of the surveys of the coast which had been then made; the wrong position on the charts of most of the numerous islands which stand out
  • 90. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com