(Ebook) Server-Side Swift by Paul Hudson
(Ebook) Server-Side Swift by Paul Hudson
com
https://ebooknice.com/product/server-side-swift-7371340
OR CLICK HERE
DOWLOAD EBOOK
(Ebook) Pro Swift - Break out of beginner’s Swift with this hands-on guide by Paul
Hudson
https://ebooknice.com/product/pro-swift-break-out-of-beginners-swift-with-this-
hands-on-guide-7371336
ebooknice.com
(Ebook) Server-Side Swift with Vapor: Building Web APIs and Web Apps in Swift by
raywenderlich.com Tutorial Team, Tim Condon, Tanner Nelson, Jonas Schwartz, Logan
Wright ISBN 9781950325276, 195032527X
https://ebooknice.com/product/server-side-swift-with-vapor-building-web-apis-
and-web-apps-in-swift-12156018
ebooknice.com
(Ebook) Building React Apps with Server-Side Rendering: Use React, Redux, and Next
to Build Full Server-Side Rendering Applications by Thakkar Mohit ISBN
9781484258682, 1484258681
https://ebooknice.com/product/building-react-apps-with-server-side-rendering-
use-react-redux-and-next-to-build-full-server-side-rendering-
applications-23963100
ebooknice.com
(Ebook) Building React Apps with Server-Side Rendering: Use React, Redux, and Next
to Build Full Server-Side Rendering Applications by Thakkar, Mohit ISBN
9781484258682, 1484258681
https://ebooknice.com/product/building-react-apps-with-server-side-rendering-
use-react-redux-and-next-to-build-full-server-side-rendering-
applications-23963280
ebooknice.com
(Ebook) Fedora 7 Unleashed by Andrew Hudson, Paul Hudson ISBN 9780672329425,
0672329425
https://ebooknice.com/product/fedora-7-unleashed-1309712
ebooknice.com
https://ebooknice.com/product/exploring-blazor-creating-hosted-server-side-and-
client-side-applications-with-c-49858114
ebooknice.com
https://ebooknice.com/product/exploring-blazor-creating-hosted-server-side-and-
client-side-applications-with-c-55536148
ebooknice.com
https://ebooknice.com/product/exploring-blazor-creating-server-side-and-client-
side-applications-in-net-7-47422604
ebooknice.com
(Ebook) Ubuntu Unleashed 2008 Edition: Covering 8.04 and 8.10 by Andrew Hudson, Paul
Hudson ISBN 9780672329937, 067232993X
https://ebooknice.com/product/ubuntu-unleashed-2008-edition-
covering-8-04-and-8-10-1266300
ebooknice.com
HACKING WITH SWIFT
4&37&34*%&
48*'5
COMPLETE TUTORIAL COURSE
www.hackingwithswift.com 2
Wrap up
Routing 178
Setting up
Chaining routes
Reading user data
Routing regular expressions
Wrap up
Templates 251
Setting up
Recap on the basics
Filters and tags
Wrap up
Barkr 265
Setting up
www.hackingwithswift.com 3
An SQL primer
Integrating MySQL with Kitura
Generating tokens
Reading insert IDs
Over to you: fuzzy search
Wrap up
Databases 316
Setting up
Indexing for performance
Normalization for efficiency
Referential integrity for organization
Transactions for consistency
Default values for safety
Wrap up
AppleFanatic 370
Setting up
Bootstrapping our servers
Fetching stories from a database
IDs, slugs, and Markdown
Stories and errors
Browsing by category
Creating an admin section
Wrap up
www.hackingwithswift.com 4
Testing 422
Setting up
Bootstrapping XCTest
Testing our routes
Wrap up
www.hackingwithswift.com 5
Preface
www.hackingwithswift.com 6
About this book
The Server-Side Swift tutorial series is designed to make it easy for beginners to get started
building web apps and websites using the Swift programming language.
My teaching method skips out a lot of theory. It skips out the smart techniques that transform
20 lines of easy-to-understand code into 1 line of near-magic. It ignores coding conventions by
the dozen. And perhaps later on, once you've finished, you'll want to go back and learn all the
theory I so blithely walked past. But let me tell you this: the problem with learning theory by
itself is that your brain doesn't really have any interest in remembering stuff just for the sake of
it.
You see, here you'll be learning to code on a Need To Know basis. Nearly everything you
learn from me will have a direct, practical application to something we're working on. That
way, your brain can see exactly why a certain technique is helpful and you can start using it
straight away.
This book has been written on the back of my personal motto: "Programming is an art. Don't
spend all your time sharpening your pencil when you should be drawing." We'll be doing some
"sharpening" but a heck of a lot more "drawing" – if that doesn't suit your way of learning, you
should exit now.
1. Follow the series: The tutorials are designed to be used in order, starting at the
beginning and working through to the end. The reason for this is that concepts are
introduced sequentially on a need-to-know basis – you only learn about something
when you really have to in order to make the project work.
2. Don't skip the technique projects: The tutorials follow a sequence that places a
technique project after every two app projects. That is, you develop two apps then we
focus on a particular component to help make your code better. The apps are
standalone projects that you can go on to develop as you wish, whereas the technique
tutorials will often be used to improve or prepare you for other projects.
www.hackingwithswift.com 7
3. Get ready to hack: This is not designed to be the one-stop learning solution for all your
Swift needs. The goal of each project is to reach the end with as little complication as
possible, while learning one or more things along the way.
I can't re-iterate that last point enough. What I have found time and time again is that any
tutorial, no matter how carefully written or what audience it's aimed at, will fail to fit the needs
of many possible readers. And these people get angry, saying how the tutorial is wrong, how
the tutorial is lame, how their tutorial would be much better if only they had the time to write
it, and so on.
Over the last 12 years of writing, I have learned to ignore minority whinging and move on,
because what matters is that this tutorial is useful to you.
You'd be surprised by how many people think the path to success is through reading books,
attending classes or, well, doing pretty much anything except sitting down in front of a
computer and typing. Not me. I believe the best way to learn something is to try to do it
yourself and see how it goes.
Sure, going to classes might re-enforce what you've learned, or it might teach you some time-
saving techniques, but ultimately I've met too many people with computing degrees who
stumble when asked to write simple programs. Don't believe me? Try doing a Google search
for "fizz buzz test", and you'll be surprised too.
So, dive in, make things, and please, please, please have fun – because if you're not enjoying
yourself, Swift coding probably isn't for you.
If you spot any errors in this book, either typos or technical mistakes, please do let me know so
I can correct them as soon as possible. The best way to get in touch is on Twitter @twostraws,
but you can also email [email protected].
www.hackingwithswift.com 8
• I’ve written these tutorials using Xcode 8.1, which is available for free from the Mac
App Store. If you’re using an earlier version of Xcode you should upgrade before
continuing otherwise you may encounter bugs.
• If you’re using Linux or considering using Linux, please read the introductory chapter
“A note on Linux”.
• Swift is a relatively new language, and is evolving quickly. Every new release of
Xcode seems to change something or other, and often that means code that used to
work now no longer does. At the time of writing, Swift is mature enough that the
changes are relatively minor, so hopefully you can make them yourself. If not, check to
see if there's an update of the project files on hackingwithswift.com.
• These projects are designed to work with Kitura 1.0 or later. Please upgrade your
system otherwise you’ll find this book very confusing indeed!
Important note: if any bugs are found in the project files, or if Swift updates come out that
force syntax changes, I'm going to be updating this book as needed. You should follow me on
Twitter @twostraws if you want to be notified of updates.
I'm also happy to answer questions on Twitter if you encounter problems, so please feel free to
get in touch!
Swift, the Swift logo, Xcode, Instruments, Cocoa Touch, Touch ID, AirDrop, iBeacon,
iMessage, iPhone, iPad, Safari, App Store, Mac, and macOS are trademarks of Apple Inc.,
registered in the U.S. and other countries.
Server-Side Swift is copyright Paul Hudson. All rights reserved. No part of this book or
corresponding materials (such as text, images, or source code) may be reproduced or
distributed by any means without prior written permission of the copyright owner.
Acknowledgements
I'd like to thank Ankit Aggarwal for his invaluable help and advice with the Swift package
manager. It's a fast-developing part of our ecosystem, but Ankit is doing a great job
documenting all the changes and supporting everyone who has questions.
I'm also grateful to Kyle Fuller for being so responsive with answers, features, and fixes to his
www.hackingwithswift.com 9
Stencil template engine. His work made my life a great deal easier, and I look forward to
seeing where Stencil goes next!
Dedication
This book is dedicated to IBM's Kitura team, who have patiently answered my many questions
on their Slack channel. Chris Bailey, Shmuel Kallner, Youming Lin, Ian Partridge, and others
– thank you!
www.hackingwithswift.com 10
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
Why does Kitura exist?
It doesn’t matter whether you’ve been using iOS, macOS, watchOS, or tvOS – they are all
very different to working on the server. Taking iOS as an example, you’re already used to the
idea that apps are built using multiple layers. Here are some of them:
1. The Swift programming language provides us with basic syntax and functionality like
func, var, as well as closures, classes, and so on.
2. The Swift standard library is a large body of code that provides basic data types and
methods: what is an Int? How do you sort an Int array? What does the print()
function do?
3. Foundation is Apple’s framework for providing extended data types, such as Date,
Data, and UUID.
4. Grand Central Dispatch (GCD or “libdispatch”) is a low-level framework for letting us
add concurrency without much of the pain. (That is, the ability to run more than one
piece of code at a time.)
5. Core Graphics, Core Image, Core Animation, Core Data, Core Text, and many other
low-level frameworks provide specific services we can draw on to solve problems.
6. UIKit is Apple’s framework for creating interactive user interfaces for iOS.
These layers build on top of each other: if you remove any of the lower layers, UIKit would
either not exist or be dramatically worse off. Together, layers 3 through 6 are sometimes
(erroneously) called “Cocoa Touch” on iOS or “Cocoa” on macOS, but it’s a helpful term
because it just means “our fundamental app building blocks.”
That list is far from exhaustive, but it gives us enough for me to describe the most important
thing you need to know: server-side Swift is Swift without most of Apple’s frameworks. Yes,
you still get the Swift language and the standard library, but you get none of the “Core” layer
(Core Graphics and so on), you get none of the UIKit, AppKit, or WatchKit frameworks, and
Foundation is incomplete.
Yes, you read that right: Foundation is incomplete. This means many methods will fail because
they haven’t been written yet, other methods might work for some specific code paths, and
other methods are implemented fully. On the bright side, you do get GCD, which works just
the same on the server as it does on Apple’s platforms.
www.hackingwithswift.com 11
the same on the server as it does on Apple’s platforms.
So, with large parts of Foundation missing, plus all “Core” and “Kit” frameworks completely
absent, server-side Swift is significantly simpler. If you followed my books Hacking with
Swift or Hacking with macOS, you’ll know that most of the learning is about figuring out how
UIKit works. Not so with server-side Swift: because it’s significantly simpler, you can spend
more time focusing on how to build projects with what you know rather than always having to
learn new things.
Because Apple’s framework footprint is significantly smaller, third-party libraries step in to fill
the gaps. That’s where Kitura comes in: it’s a framework developed by IBM to provide the
tools we need to build web apps and websites. There are four main web frameworks at the time
of writing, but I chose Kitura for this book for a number of reasons:
Each of those reasons is compelling by itself, but there’s another important reason that really
shapes the way you work with server-side Swift: Kitura is highly modular. This means you use
the basics of Kitura to handling fundamental functionality, but after that you can pick and
choose components from elsewhere to solve whatever problems you have.
In this book, I’ll be using Kitura for as much as possible, because it comes with a lot of the
functionality we need to build great web apps. However, I’m not an API zealot: when
alternatives such as Vapor do something better, we’ll be using that. Remember, Kitura is
modular, so you can plug other components in as needed – this is by design, and means we can
all use what works best rather than being constrained to one specific approach.
So, although we lose large parts of Foundation and all the higher frameworks, many gaps are
filled by frameworks such as Kitura. And when Kitura alone isn’t enough, we’ll be drawing on
other frameworks such as Vapor – as long as it’s Swift, it’s available for us to draw on.
www.hackingwithswift.com 12
A note for existing Swift developers
If you’ve written Swift for one of Apple’s four platforms, moving to server-side Swift can be a
bit of a shock. As I’ve said, it’s simpler, but “simple” and “easy” aren’t the same thing.
Sure, server-side Swift doesn’t have UIKit, AppKit, Core Graphics, and so on – massive APIs
that take months to learn and years to master. But in their place, you’ll find a huge range of
things that web developers take for granted: sessions, templates, forms, routing, HTTP
methods, and more. Databases alone are so big, and so utterly fundamental to any website of
note, that there are 1000-page books dedicated to them.
You'll also find that server-side Swift develops significantly faster than iOS, macOS, or other
Apple platforms. Not only does Apple create yearly releases, but they also have extremely
extended deprecation periods – you can rely on deprecated APIs to carry on working for three
to five years before they are finally removed entirely. Not so on on the server: often releases
happen every week, and it's common to see breaking changes come and go rather than have a
gentle deprecation period.
Because many of these things are likely to be new to you, I want to place a message of
encouragement early on in this book: if you find yourself thinking that all this web stuff is
hard, you’re right – it is hard. But I’ve done my best to explain everything slowly, carefully,
clearly, and thoroughly, so I hope you’re able to stick with it. If (when!) you find that APIs
have been changed between me writing this book and you reading it, email me at
[email protected] and I'll do my best to help.
The complexity of server-side Swift is such that this book is a little different from my others.
More specifically, although I still try to teach things in a linear fashion, the projects aren't
strictly graded by difficulty. Even more specifically, I've inserted two easier projects part-way
through the series to help break up the flow, because without them it can just seem like an
overwhelming amount of hard work.
Trust me, by the time you reach project 5 (the first of the easier projects) you'll be more than
ready for a break!
www.hackingwithswift.com 13
Configuring your machine
Working with server-side Swift is quite different from client-side Swift such as iOS and
macOS for one large reason: macOS is very rarely used on servers. It’s possible to use macOS
for your web server, but this usually only happens if someone desperately needs macOS
features such as Xcode running on a remote server.
Instead, servers are primarily the domain of Linux, an open-source operating system that has
some things – but not many! – in common with macOS.
When Swift was open sourced in December 2015, Apple shipped Swift and the standard
library for macOS and Linux. They also shipped a limited version of Foundation, which has
slowly been improving over subsequent months.
IBM’s Kitura framework, along with the various Kitura-related components that IBM
provides, are also designed to work on macOS and Linux, so as long as you stay within the
boundaries of the Swift standard library, the open-source Foundation framework and Kitura,
your code should work identically on both macOS and Linux.
Now, “should” is a complex word that really means “in theory this does what I think it does,
but in practice I bet it doesn’t.” The problem is two-fold:
Now for the complicated part. If you’re already an iOS or macOS developer, you’re used to the
concept that your entire environment is dictated by your Xcode version number. Which SDKs
you have, what Swift compiler version you have, how your storyboard editor looks, and so
forth are all decided by your Xcode version.
Not so in server-side Swift. You might code on macOS and deploy to Rackspace Cloud
www.hackingwithswift.com 14
running Ubuntu 16.04, or you might code on Linux and deploy to IBM Bluemix running
Ubuntu 14.04. Each of those environments are very different, and although Swift itself will be
the same everywhere the environment it runs in will vary.
No matter what you choose, ultimately your code needs to run on Linux. That in turn means it
needs to avoid using the incomplete parts of Foundation, and requires you to be careful about
case sensitivity in filenames.
The best way to ensure you’re working correctly is to build and run your code on Linux every
step of the way. You can code on macOS if you want, it doesn’t really matter – but you do
need to build and run on Linux, to ensure what you’ve written can be deployed to a real server.
If you aren’t already running Linux as your desktop operating system, there are four options
you can take:
1. Use virtualization software such as VMware Fusion or Parallels. This lets you install a
full version of Ubuntu Linux locally, for coding and testing.
2. Set up a cloud server using something like Digital Ocean. This costs about $5 per
month, or less if you pause the instance when you don’t need it.
3. Use Docker, which is a bit like an invisible virtual machine running Linux on macOS.
(Note: it still reads and writes from your macOS hard disk, so it does not solve the
case-sensitivity problem.)
4. Pretend Linux doesn’t exist, and build and run everything on macOS.
Of the four options, #3 is by far the most popular. Docker is a free program you can install, it
lets you create Linux containers that are pre-configured for running Kitura, and it blurs the
lines between macOS and Linux because you can write your code on macOS and run it inside
the Linux instance.
Before you can continue with this book, you need to decide which of the four options you
want. You can’t not choose – you need to pick one. If you’re not sure, go with #3. Later
projects require you to install database software, and this is significantly easier if you use
Docker. Trust me on this: although it’s a little harder to get started, I strongly recommend you
choose Docker.
www.hackingwithswift.com 15
If you chose #1 or #2, please go ahead and install Ubuntu now, either locally or in your
preferred cloud provider. When installation has finished run these commands:
Finally, download and extract the correct Swift version for your Ubuntu version from https://
swift.org/download/#releases.
If you chose #4, please make sure you have Xcode 8.1 installed from the Mac App Store.
That’s it. Yes, #4 is easy, but trust me: it’s extremely easy to create problems for yourself
down the line, and you’ll need to troubleshoot them yourself.
If you chose #3, go to https://docs.docker.com/docker-for-mac/ and click “Get Docker for Mac
(stable)” to download the latest version of Docker. When the DMG has downloaded, double-
click it to open, then drag it to Applications. Once it has finished copying, browse to your
Applications folder in Finder and double-click Docker to start it – you’ll be asked to enter your
admin password in order to complete setup.
To make things simple, I’ve crafted one Docker command that does everything you need to
create, start, and gain access to an environment where you can run your projects. Once you’ve
installed the Docker app and started it, you should see a whale icon in your Mac’s status bar -
that shows the Docker virtualization system is running.
Open a terminal, then run these commands to create a directory on your desktop where you’ll
store all your server projects:
cd Desktop
mkdir server
cd server
www.hackingwithswift.com 16
Note: It’s possible your terminal starts you at a different location. If you see “~” in there then
the commands above are correct, but if you see “~/Desktop” or similar then you’re already in
your Desktop directory and can skip the first command.
That creates a directory called “server” and changes into it so that it’s the current working
directory. Now run this command:
Yes, that’s quite a lot, but it’s because I’ve tried to cram everything into one!
• Tell Docker that we want to run a command in a new container – an isolated virtual
machine that will run Linux.
• Request an interactive terminal (“it”), which is something we can type commands
using /bin/bash – the default Linux terminal.
• Attaches a volume (“v”), which means “/projects” inside the container will refer to the
current working directory.
• Tells Docker that we want to map our network port 8089 to the container’s port 8089,
map our network port 8090 to the container’s port 8090, and our network port 5984 to
the container’s port 5984. More on that in a moment!
• Names the container “projects” (“--name projects”) so we can refer to it more easily.
• Sets the working directory to be “/projects” so we start ready to go.
• Tells Docker to build the container using “twostraws/server-side-swift”, which is a pre-
configured Docker container that I’ve designed to make this book easy to follow. It
contains everything we need to get started.
When you run that command Docker will need to download all the components required to
make the container work, including Ubuntu itself as well as my customizations. If you’re
curious, my customized version updates all the software, adds Swift, Curl, CouchDB, and
www.hackingwithswift.com 17
MySQL, ready for all the projects in this book, and is based on IBM’s own Docker container.
After a few minutes you’ll find yourself looking at a terminal prompt like this:
root@f2429f0045db:/projects#
That means installation has now completed: you’re now in the “projects” directory inside the
container. This is mapped to the current working directory, so if you create any files here
you’re really creating files in the “server” directory on your Mac’s desktop, and if you change
any files in macOS those changes will be reflected in the Docker container.
Using one Docker container for all projects isn’t the preferred way of working, but it’s fine for
beginners. When you become more experienced you’ll start creating individual containers for
each project, and indeed each part of a project, but the single-container approach makes life
easier for now.
The command you ran bridged the network ports 8089, 8090, and 5984 inside the container to
ports 8089, 8090, and 5984 on your Mac. What this means is that if you try access any of those
ports on your Mac, you get seamlessly transferred to the container.
We did this because the Kitura server runs on port 8090 by default, so it allows us to test
content directly from a web browser on your Mac. Port 5984 isn’t used until project two, and
8089 isn’t used until project eleven, but we need to configure both them and 8090 now, when
creating the container. You’ll see this in action soon enough!
Before we’re done, I want to show you a few important Docker commands to help you get into
and out of your container.
root@f2429f0045db:/projects#
I say “like” because the string of letters after the @ sign will be unique to you – container IDs
are created randomly. The # sign means you’re currently root, so you have full control over the
virtual system, and we’ll be using that to install extra software later on.
www.hackingwithswift.com 18
Try running the command exit now, and after a few seconds you’ll be back to your regular
macOS terminal prompt. What you just did was quit your Docker terminal, which effectively
terminates the container. It still exists on your disk, but because “/bin/bash” was the main
process of the machine and we just quit it, the container will cease running.
Now that you’re back on the macOS terminal, run this command: docker ps. This shows a
list of running containers, and you’ll see it doesn’t show any containers. Instead, you’ll see just
some column headers where information would be, such as “CONTAINER ID”, “IMAGE”,
and so on.
The list is empty because it shows only running containers, and exiting our container stopped it
from running. We can ask for a list of all containers, running or otherwise, with this command:
docker ps -a. Note the extra “-a” in there. This time you’ll see the “projects” container
listed, and it will have the status “Exited”.
We gave our container the name “projects” so that it’s easy to refer to, so let’s start it now: run
docker start projects then wait a few seconds. You should see “projects” written
back to your terminal window, then your regular macOS command prompt. That’s Docker’s
extremely laconic way of saying “your container is now running.”
To verify that “projects” is active, try running the docker ps again. This time you’ll see
your container listed with the status “Up about a minute”, showing that it’s active. This time,
though, it’s active without us having a Bash terminal inside, so we can carry on working inside
the macOS terminal as if Docker weren’t there.
So, now we have a fully configured Kitura Docker container up and running, and it’s
effectively invisible – you could quit the Mac’s Terminal app altogether and Linux would
carry on running in the background. This is the preferred state for containers once you’ve
finished development: you start them up, then forget about them.
Of course, sometimes you’re going to want to get back into the container to make changes.
Later on, for example, we’re going to be installing MySQL inside the container so that we
have access to a database. To do that, you need to attach to a container that’s running – to
connect to its existing Bash terminal so you’re back at the root prompt.
To attach to the “projects” container, run this command: docker attach projects.
www.hackingwithswift.com 19
You might need to press Return a couple of times, but after a few seconds you should be back
at the root prompt inside your container. During development – when you need to run builds
frequently – I usually keep the container attached for easy access.
Tip: If you want to start your container and attach at the same time, use docker start -i
projects.
Now that you’re back inside the container, running exit will make it terminate just like
before. More commonly you’ll want to detach from the container, which means “get me back
to my macOS terminal, but leave the container running.” This is done using two special
keystrokes: Ctrl+p followed by Ctrl+q. These should be pressed one after the other rather than
together.
When you press those two, you’ll immediately be returned to your macOS terminal, but the
“projects” container will carry on running. You can attach again using docker attach,
then detach, attach, detach, and so on; it will just carry on running.
If you ever want to destroy the container, use docker rm projects. If it’s currently
running you’ll be told to stop it first, or add the -f parameter to force removal.
One last thing before we’re done with Docker: once you’ve created your Kitura container,
Docker automatically saves the image required to recreate it. This means you can create more
containers from the same image – “ibmcom/kitura-ubuntu” – in just a few seconds, because
Docker doesn’t need to download it again.
Once again, Docker really is the preferred approach to server-side Swift development. With
the setup above, you’re able to write your code using your preferred macOS tools, test using
your preferred macOS web browser, but build and run using Linux. This means you’re in the
perfect position to transfer your code to a real server when you’re ready, without having to
constantly transfer files along the way.
www.hackingwithswift.com 20
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
Introduction
If you want to learn the language all at once before you start making apps, this is for you.
www.hackingwithswift.com 21
How to install Xcode and create a playground
Xcode is Apple's programming application for developers. It's free from the Mac App Store,
and it's required to do iPhone and iPad development. So, your first action is to click here to
install Xcode from the Mac App Store – it's quite a big download, so start downloading it now
and carry on reading.
While that's downloading, I can explain a couple of the absolute basics to you:
• iOS is the name of the operating system that runs on all iPhones and iPads. It's
responsible for all the basic operations of the phone, such as making phone calls,
drawing on the screen, and running apps.
• macOS is the name for Apple’s desktop operating system, which is the technological
grandparent of iOS, tvOS, and even watchOS.
• Swift is Apple's modern programming language that lets you write apps for iOS,
macOS, and other platforms. It contains the functionality for building programs, but
doesn't handle anything like user interfaces, audio or networking.
• Swift 1.2 was the first major update to Swift, tweaking various language features and
improving others.
• Swift 2 was the second major update to Swift, introducing checked exceptions, and
many other major improvements.
• Swift 2.2 was a minor update to Swift 2.0, deprecating some syntax ahead of its
removal in Swift 3.
• Swift 3 is the third major update to Swift, and is the version used throughout Hacking
with Swift.
• UIKit is Apple's user interface toolkit. It contains things like buttons, text boxes,
navigation controls and more, and you drive it using Swift.
• Cocoa Touch is the name commonly used for Apple's vast collection of frameworks
for iOS. It includes UIKit to do user interfaces, but also SpriteKit for making 2D
games, SceneKit for making 3D games, MapKit for maps, Core Graphics for drawing,
Core Animation for animating things, and much more.
• Cocoa is the name used for Apple’s framework collection on macOS. Strictly speaking
it’s made up of AppKit for user interface, Foundation for basic functionality, and Core
Data for object graphs, but like Cocoa Touch it’s often used to mean “all of macOS
development.”
www.hackingwithswift.com 22
• NeXTSTEP is an operating system created by a company that Steve Jobs founded
called NeXT. It was bought by Apple, at which point Jobs was placed back in control
of the company, and put NeXTSTEP technology right into the core of Apple's
development platform.
• iOS Simulator is a tool that comes with Xcode that looks and works almost exactly
like a real iPhone or iPad. It lets you test iOS apps very quickly without having to use a
real device.
• Playgrounds are miniature Swift testing environments that let you type code and see
the results immediately. You don't build real apps with them, but they are great for
learning. We'll be using playgrounds in this introduction.
• Crashes are when your code goes disastrously wrong and your app cannot recover. If a
user is running your app it will just disappear and they'll be back on the home screen. If
you're running in Xcode, you'll see a crash report.
• Taylor Swift has nothing to do with the Swift programming language. This is a shame,
as you might imagine, but I'll try to make up for this shortfall by using her songs in this
tutorial. Deal with it.
That's it for the basics – if Xcode still hasn't finished downloading then why not watch some
Taylor Swift videos while you wait? The examples in this tutorial will certainly make a lot
more sense…
www.hackingwithswift.com 23
Xcode will ask you whether you want to create a playground for iOS or macOS, but it doesn’t
matter here – this introduction is almost exclusively about the Swift language, with no user
interface components. For the avoidance of problems, leave “iOS” selected for the platform.
What you'll see is a window split in two. On the left you'll see this:
import UIKit
This split is important, because it divides code and results. The code is in the left pane, and you
will edit this to do your own Swift work as we go. The results are in the right pane, and it
shows you what your Swift code has done. In this case, it's telling us that we successfully set
the value "Hello, playground."
You will also notice that the very first line of the playground starts with two slashes, //. When
www.hackingwithswift.com 24
Swift sees two slashes like that, it ignores everything after them on a line. This is commonly
used for comments: notes that you write into your code to help you understand what it does
later.
As you type, the playground will automatically run your code and show the updated results.
For example, if you just write str by itself, you'll see "Hello, Playground" twice on the right –
once because it's being set, and once because you're printing the value.
Playgrounds are a great way to try some code and see the results immediately. They are
extremely powerful too, as you'll see over the next hour or so. Let's get started writing Swift!
www.hackingwithswift.com 25
Variables and constants
Every useful program needs to store data at some point, and in Swift there are two ways to do
it: variables and constants. A variable is a data store that can have its value changed whenever
you want, and a constant is a data store that you set once and can never change. So, variables
have values that can vary, and constants have values that are constant – easy, right?
Having both these options might seem pointless, after all you could just create a variable then
never change it – why does it need to be made a constant? Well, it turns out that many
programmers are – shock! – less than perfect at programming, and we make mistakes. One of
the advantages of separating constants and variables is that Xcode will tell us if we've made a
mistake. If we say, "make this date a constant, because I know it will never change" then 10
lines later try to change it, Xcode will refuse to build our app.
Constants are also important because they let Xcode make decisions about the way it builds
your app. If it knows a value will never change, it is able to apply optimizations to make your
code run faster.
In Swift, you make a variable using the var keyword, like this:
Let's put that into a playground so you can start getting feedback. Delete everything in there
apart from the import UIKit line (that's the bit that pulls in Apple's core iOS framework
and it's needed later on), and add that variable. You should see the picture below.
www.hackingwithswift.com 26
Because this is a variable, you can change it whenever you want, but you shouldn't use the
var keyword each time – that's only used when you're declaring new variables. Try writing
this:
So, the first line creates the name variable and gives it an initial value, then the second line
updates the name variable so that its value is now "Romeo". You'll see both values printed in
the results area of the playground.
Now, what if we had made that a constant rather than a variable? Well, constants use the let
keyword rather than var, so you can change your first line of code to say let name rather
than var name like this:
import UIKit
let name = "Tim McGraw"
name = "Romeo"
But now there's a problem: Xcode is showing a red warning symbol next to line three, and it
should have drawn a squiggly underline underneath name. If you click the red warning
symbol, Xcode will tell you the problem: "Cannot assign to 'let' value 'name'" – which is
Xcode-speak for "you're trying to change a constant and you can't do that."
So, constants are a great way to make a promise to Swift and to yourself that a value won't
www.hackingwithswift.com 27
change, because if you do try to change it Xcode will refuse to run. Swift developers have a
strong preference to use constants wherever possible because it makes your code easier to
understand. In fact, in the very latest versions of Swift, Xcode will actually tell you if you
make something a variable then never change it!
Important note: variable and constant names must be unique in your code. You'll get an error
if you try to use the same variable name twice, like this:
If the playground finds an error in your code, it will either flag up a warning in a red box, or
will just refuse to run. You'll know if the latter has happened because the text in the results
pane has gone gray rather than its usual black.
www.hackingwithswift.com 28
Types of Data
There are lots of kinds of data, and Swift handles them all individually. You already saw one
of the most important types when you assigned some text to a variable, but in Swift this is
called a String – literally a string of characters.
Strings can be long (e.g. a million letters or more), short (e.g. 10 letters) or even empty (no
letters), it doesn't matter: they are all strings in Swift's eyes, and all work the same. Swift
knows that name should hold a string because you assign a string to it when you create it:
"Tim McGraw". If you were to rewrite your code to this it would stop working:
var name
name = "Tim McGraw"
This time Xcode will give you an error message that won't make much sense just yet: "Type
annotation missing in pattern". What it means is, "I can't figure out what data type name is
because you aren't giving me enough information."
At this point you have two options: either create your variable and give it an initial value on
one line of code, or use what's called a type annotation, which is where you tell Swift what
data type the variable will hold later on, even though you aren't giving it a value right now.
You've already seen how the first option looks, so let's look at the second: type annotations.
We know that name is going to be a string, so we can tell Swift that by writing a colon then
String, like this:
You'll have no errors now, because Swift knows what type of data name will hold in the
future.
Note: some people like to put a space before and after the colon, making var name :
String, but they are wrong and you should try to avoid mentioning their wrongness in polite
company.
The lesson here is that Swift always wants to know what type of data every variable or
www.hackingwithswift.com 29
Random documents with unrelated
content Scribd suggests to you:
They visited ancient Memphis, which the French explorer, Mariette, was
then exhuming, and trod the pavements over which had passed the feet of
Menes, Amasis, Pharaoh, Strabo, and Cambyses. They were hospitably
entertained by the great antiquarian, and felt that such a visit was ample
reward for all their outlay. From Memphis they proceeded to Siout, and on the
way talked, composed, and sung the praises of Father Nile. It may be that Mr.
Taylor’s mood, which he so often mentions, had an influence upon his taste,
or it may be that the season was one peculiarly adapted to the exhibition of
beauty in the Nile, but the writer, in a later year, was not so charmed by the
scenery and river as Mr. Taylor appears to have been. No other traveller has
written such glowing encomiums upon the Nile as Mr. Taylor recorded in his
letters, and either he appreciated nature more than other travellers, or there
was something in his circumstances which placed a halo of beauty about the
palms and meadows. In the “Nilotic Drinking-Song” Mr. Taylor said:—
His admiration was not spasmodic, for he always mentioned the Nile as the
most majestic of rivers. To the majority of travellers, however, the hoary ruins
of mighty cities, the tombs of priests, and the pyramids of kings are so much
more exciting and mysterious, that the Nile is itself of secondary importance.
Yet, Mr. Taylor, with all his interest in the river, did not have less in the
celebrated localities and ancient remains. He ascended many honeycombed
mountains, to creep among the bones of men who lived thirty-five hundred
years ago. He gazed with a yearning interest upon the broken columns of
unknown temples, and dreamed of their former grandeur, while apathetically
overseeing the affairs of his little monarchy over which he kept floating the
Stars and Stripes. He became so absorbed in the climate, the people, and the
history of the land, that he soon adopted the full costume of the country and
became henceforth an Arab with the others. He was marvellously quick in
picking up the words and phrases of any language, and soon, with the aid of
a small phrase-book, he could readily converse with the natives along the
shore. These characteristics made it safe and pleasant for him to travel where
many others would have found only misery and death.
CHAPTER XVIII.
Moslem Worship.—Scenery of the Nile.—Fellowship with the People.—The
Temple of Dendera.—Mr. Taylor’s Enthusiasm.—Luxor.—Karnak.—The
Extent of Ancient Thebes.—The Tombs and Statues.—The Natives.—
Arrives at Assouan.—The Island of Philæ,—Separation of the Friends.—
Starts for the White Nile.—Trip through the Desert.—Again on the Nile.
—Reception by the People and Officials.—Visits Ancient Meroe.
Mr. Taylor’s sympathy with all mankind led him to regard with sincere
respect the daily religious ceremonies which his Moslem boatmen performed,
with their faces toward Mecca. He often mentioned their punctuality and
apparent sincerity, and contrasted it with some of the formal, half-hearted
proceedings in some Christian churches. His regard for conscientious worship,
which appeared to characterize the ignorant Arabs, appears more striking to
persons who have travelled the same route over which Mr. Taylor went, for it
is so common a sight to see bigoted, conceited Europeans ridiculing the
prostrations, prayers, and gestures of the worshippers. The writer most keenly
regrets having been compelled to witness the caricaturing of a Moslem at
prayer, by a coarse, hard-hearted, brutal Christian countryman, while the sad
and shocked believers in Mahomet stood by, scarce able to resist the
temptation to throw the Frank into the Nile. In the lovable, noble character of
Mr. Taylor, there was no inclination to ridicule the conscientious belief of any
man, and instinctively he kept silent and patiently endured the delay when the
call to prayer took his employees from their labor. In return for his sincere
regard for them, he received the love and most faithful service of the natives.
They stole nothing from him. They shielded him from enemies and
affectionately cared for his health.
Thus, with friends for boatmen, an admirer for a guide, and a most
agreeable comrade for a travelling companion, he floated along, inhaling from
every breeze the essence of health and comfort. The banks were covered with
the richest and rarest verdure, for it was the Egyptian spring. There were
luxuriant grasses, palms and sugar-cane; there flourished wheat, cotton,
maize, hemp, indigo, tobacco, oranges, olives, and dates, springing from the
richest soil which civilized man has yet seen. Harvests came and went in
confused succession; the ripe fruit with blossom; threshing-floors piled with
ripe dourra, while around, the new wheat seeking the sunlight, betokened a
bounty munificent and inexhaustible. So prolific and speedy was the growth of
the crops that the people could not, with their rude implements, avail
themselves of the full benefits of one harvest before its rank successors
forced them to turn their labor into other channels. Then, as now, the fields,
for miles inland from the river, were checkered with canals, and the rude
water-wheel and awkward “well-sweep” were kept in constant motion to
supply the vast amount of water necessary to the irrigation of hundreds of
square miles. There were goats, mules, horses, and a variety of fowl, and in
the wild nooks a grand collection of birds of the gayest songs and plumage.
The sky was clear, the air balmy, the breezes cool and light, the cabin of their
boat was spacious, and their beds comfortable. It was “a soothing experience
for an aching heart.”
In the first week of December they arrived at Dendera, where stands in
majestic completeness one of the most ancient temples of Egypt. It has for
thousands of years been half buried in the earth, and at one time must have
been nearly hid by the shifting sands of the desert which once surrounded the
pile. The impression which the gigantic columns, sixty feet high, and the
enormous blocks of stone, eight feet thick, gave to them, is doubtless shared
in some degree by all travellers. As he walked through the shadowy recesses,
each aperture seeming like a deep cave in a rocky mountain, he was filled
with a solemn sense of awe and sadness, which so overwhelmed him that he
peered about the avenues in silence, and involuntarily stood on tip-toe. The
sombre grandeur of the massive masonry, the sacred associations connected
with the ancient worship of Osiris and Isis, the wonderful tales of wars,
tyrannies, famines, plagues, Rameses, Moses, Pharaoh, Alexander, Ptolemy,
Cambyses, and Napoleon, which those lofty statues could tell if their
symmetrical lips could speak, awaken indescribable emotions, deep, thrilling,
and permanent. Mr. Taylor saw a grace and an artistic merit in the stone
figures, and in the hieroglyphics that adorned the temple, which few travellers
detect or admit. To many travellers the figures on those old porches and halls
seem rude and often out of proportion, and the writer confesses to having
been one of the latter class. But Mr. Taylor’s appreciating scrutiny may be
accounted for on the basis that with his poetical instincts and thorough
culture in art, there were beauties in those works of ancient sculptors, latent
to others, but apparent and striking to him. But there is no disagreement as
to the unspeakable solemnity of the place and the gloom of its lonely halls.
The next night they reached Luxor, and caught the first glimpse of those
interesting ruins by moonlight. There, silent and stately, arose the great
Colonnade. There, quietly recalling the ancients, stood the twin Obelisk to the
one at which Mr. Taylor had often looked in the Place de la Concorde in Paris,
when as a boy he dreamed of distant Egypt. For seven miles around the
Temple of Luxor are the ruins of ancient Thebes, within which were once the
temples of Karnak, Luxor, Goorneh, Memnonium, and hundreds more, which
now cumber the otherwise fertile plains. Thebes, with its hundred gates, with
its countless armies, with its wise men, its Colossus that sang in the morning
sunlight, its avenues of sphinxes and gods in stone, lay broken, spurned, and
dead before them. The same moon looked down on them that gazed on the
priests of Isis and the palace of its Cæsars. No one can imagine anything so
solemn and grand as to stand in the moonlight on the haunted plains of
ancient Thebes! One may have thought the Coliseum at Rome impressive
beyond description when seen in the favorable light of an autumn moon, but
when compared with Thebes it is tame and insignificant. Ages and ages
before the rape of the Sabines, these temples had been constructed. They
saw the morning of civilization; but now they are ruined and useless, the
night seems best fitted for an appreciative view of them. Among the mighty
colonnades whose columns are broken and falling, and around gigantic
remains of ancient statues carved from a mountain of stone, Mr. Taylor
wandered for two whole days. He scrutinized closely the long rows of ancient
tombs, and stood in the rocky grave of Rameses I. The pictures on the walls
of the tombs, the kind of rock, the original shape of the temples, the
employments of the ancient races, the blue sky overhead, the clear
atmosphere around, together with sketches of history and poetical allusions,
shared in the interesting letters which Mr. Taylor wrote from Thebes. Such
scenes contain an inspiration and an education which make scholars and
statesmen of such as love history and appreciate the lessons those ruins
teach. To one of Mr. Taylor’s disposition, a visit to such a place was a privilege
not to be lightly thrown away. He investigated everything, and in a manner
bordering on recklessness he descended through small holes into dark
subterranean tombs, and with equal hardihood walked the crumbling roofs
and cornices of the lofty ruins. He looked with disgust on the evidences of
spoliations which were to be seen in splintered columns and fragments of
ancient frescoes, and which were the work of scientific explorers. He regarded
with a jealous anxiety the evidences of vandalism and decay, and wished
sincerely that time and man would allow those precious relics of the old
régime to remain forever intact. He appears to have regarded those massive
wrecks as half-human, and sympathized with their forsaken and friendless
condition.
But in all this antiquarian excitement, which usually occupies the undivided
attention of less enthusiastic travellers, Mr. Taylor neglected not the living. He
witnessed with interest the graces of the Arabian dancing-girls, noticed the
features of the beggar-boys, the methods of teaching children the Koran, and
the worn appearance of the water-carriers.
Leaving Luxor, they spent three or four days ascending the river to
Assouan, and in visiting the villages, old temples, half-buried cities, and
gorgeously decorated tombs in the mountain-sides, which are almost
numberless in the valley of Upper Egypt. At Assouan, he was most cordially
received by the Governor and was given a friendly greeting by all the officials
he met. From that town he made several excursions with his German friend,
the most interesting of which was that to the cataract of the Nile and the
island of Philæ. There he saw the celebrated temple of the time of the
Ptolemies, which he looked upon as modern, because it was not over twenty-
two hundred years old. But he felt sufficient interest in the ruins of the old city
to describe that marvellous colonnade which has astonished so many visitors
to the island of Philæ. The reader of his letters can detect, however, in Mr.
Taylor’s description of columns, aisles, roofs, walls, capitals, sculptures,
monoliths, and colossi, a vein of sadness which may have colored his views.
At all events the ruins of Philæ did not impress him as they seem to have
affected other visitors. The fact that he was so soon to part with a companion
for whom he felt a love like that of Jonathan for David, may have had more or
less influence upon his capacity to enjoy scenery or the remains of antiquity:
for the writer looked upon Philæ as one of the most interesting localities of
the lower Nile, and cannot but regard the ruined temple as one of the
grandest in Egypt. They visited the fields, villages, the tombs, the ancient
quarry, wherein half-sculptured statues and columns still remain unmoved,
and after a day of antiquarian research they rode back to their boat, as he
said “with heavy hearts.” The next day came the hour of parting; and these
two men, one a young man, the other an elderly gentleman, who had been
utter strangers forty days before, now clung to each other with the sincerest
brotherly love and parted in tears. How little did Mr. Taylor think, as he saw
the boat sailing away for Cairo with the Saxe-Coburg colors at the peak,
where he had so long kept the Stars and Stripes, that they would meet again
in the sunny southern lands of Europe, and that another person would join
their company for life and make up what he termed “a sacred triad.” He
thought then that the parting might be for all time. He was going into an
unknown wilderness, while his friend sought again the lands of civilization: it
was a long time before either could dispel the gloom which their separation
left about them.
PHILÆ COLONNADE.
Mr. Taylor took another boat at Assouan and proceeded to Korosko, where,
with the assistance of the Governor and a wild Arab chieftain, whose
friendship was purchased by presents and sociability, he secured the
necessary camels and outfit for a trip across the desert. It was a hazardous
undertaking for a stranger, alone, unknown, to traverse the desert. If he was
murdered, none of the authorities would care, nor would his death become
known. He might contract the terrible fever. He was liable to be eaten by wild
beasts, and he ran great risk of dying of thirst or hunger on the hot sands of a
trackless desert. The way had been travelled many times before, but was all
the more dangerous because of the opportunity it gave robbers to lie in wait
for tourists. But he unhesitatingly entered upon the journey, trusting in the
friendship of his Nubian and Arabian servants, and in his own ability to
withstand the heat of the sands and the attacks of African fever. Camping in
the desert sands, riding a dromedary in the scorching sun, living upon rudely
prepared food, drinking lukewarm water, with the sight of bones and
carcasses by the way to warn him, and the occasional appearance of sickly
returning caravans to dishearten him, he passed that arm of the desert
between the first cataract of the Nile and Abou-Hammed. Thence his little
caravan of six camels followed the winding river to a small town, El
Mekheyref, where he dismissed his friendly companions, excepting one, who
had accompanied him from Cairo, and set sail again on the Nile. Everywhere
he was received with kindness and hospitality by the natives and by the
Governors. His servants were so much interested in his welfare that they told
the natives that he was a high official in the country from which he came, and
he was treated with the respect the Eastern people think is due to persons of
high rank. All disclaimers from him were considered to be actuated by feelings
of modesty and elevated him in the estimation of his entertainers.
His visit to Meroe was an interesting episode in his long pilgrimage,
although he did not make such diligent search as an antiquarian among its
crumbling walls as he had done in some of the other ancient cities. Yet his
descriptions of that place are most vivid pictures and convey an idea of the
topography of the capital of that ancient kingdom in a manner most readable
to the stranger and very important to students of history.
CHAPTER XIX.
From Meroe to Khartoum.—Twenty-seventh Birth-day.—Desire to Explore
Central Africa.—Ascent of the White Nile.—Adventure with the Savage
Shillooks.—Visits the Natives.—Return to Khartoum.—Crossing the
Desert.—Parting with Friends.—Descent of the Nile.—Arrival at Cairo.
The journey from Meroe to Khartoum on the Ethiopian Nile, Mr. Taylor
enjoyed very much, having little to do but amuse the sailors and be in turn
amused with stories of Mohammed, of Haroun-al-Raschid, and the oriental
wonders contained in songs and traditions. The climate gave him health, his
genial good-nature brought him friends, and his experience would supply the
necessities of life in after years. There were narrow escapes from animals,
men, and treacherous rapids; but he had become accustomed to such things,
and assumed enough of the Arab character to exclaim with them, at each
escape, “It is the will of Allah.” The day before he arrived at Khartoum was Mr.
Taylor’s twenty-seventh birthday.
Having letters to many of the officials of Khartoum, which was a military
and trading station at the junction of the Blue and the White Nile, he received
a cordial welcome, which made him feel at once that he was among friends.
He was then at the extreme outskirts of civilization. All beyond was dark and
unknown. Trading caravans consisting of Arabs and natives often visited the
interior, and small boats frequently went farther up the Nile for purposes of
traffic. But there was little known about the people, the topography of the
country, or of the course of the Nile. There was a Catholic mission at
Khartoum, where the missionaries treated Mr. Taylor with great consideration
and kindness. Some of them had made exploring excursions into the wilds of
Central Africa, and it was his hope that he could get into some expedition with
them during that season. But in that he was disappointed. None of the
missionaries were intending to visit the tribes to the south that season, and
no other suitable opportunity presented itself. He did not give up the hope of
seeing the unexplored regions of the interior, until he had exhausted every
means in his power for procuring a fit escort. The unfortunate combination of
circumstances, which prevented him from searching for the sources of the
Nile, postponed the revelations which he would have made, until they were
unfolded by another newspaper correspondent, H. M. Stanley.
So persistent was Mr. Taylor in his purpose to travel beyond the boundaries
of the known, that he resolved to go up the White Nile alone, except a few
servants. He had met Captain Peele, whose accounts of the curiosities to be
found farther inland made him the more anxious to get a glimpse beyond. So
he hired a boat, and amid the doubts of his servants and the misgivings of his
new-found friends, he set sail up the White Nile. He could not hire the
boatmen for a long voyage, as they feared the fierce cannibals of the interior,
and as they were going beyond the protection of any military force. Trusting
to his persuasive powers, he started with them, deciding to go just as far as
he could get them to accompany him.
On a lone river, where no other sail was to be seen; in a wilderness, where
even the human beings were as the lions and hyenas; with no friend of his
own race near him, he sailed on, in confidence, never seeming to think that
he might die there alone and never be heard of by his relatives again.
Crocodiles, hippopotami, and giraffes flourished there, and man was the
plaything of both elements and beasts. Through the wildest scenery, among
the strangest birds and animals, he pursued his course, trembling night and
day lest his crew should at any moment refuse to go farther.
At last they came to the country of the Shillooks. That wild tribe of negroes
was known to the boatmen through nursery tales and traditional stories,
wherein the savages were given very bad names; and when Mr. Taylor
informed them that he purposed to visit the village of those horrid man-
eaters, they regarded him with looks of the most profound astonishment. But
with a hardihood that by its boldness secured acquiescence, he commanded
them to row him to the banks of the Nile, where the long rows of primitive
huts were to be seen. Through captives and merchants the kingdom of the
Shillooks had become partially known, and a kind of jargon, like the pigeon-
English of the Chinese, served the purposes of communication. One of Mr.
Taylor’s company could talk with them slightly, and with him as an interpreter,
and another servant for a protector, he walked boldly into the village of the
savages, taking no weapons, lest he should create suspicion. But they
received him coldly and with much show of suspicion and treachery. It was a
most dangerous experiment, and it is a matter of wonder that he was allowed
to depart. There were large numbers of armed men around him, brandishing
spears and clubs, and demanding of him all sorts of impossible presents. But
with a calmness and seeming confidence, Mr. Taylor smoked with the chief,
and exchanged presents with the subordinate officials, until they became
friendly and docile, laying down their weapons and conversing cheerfully
through the interpreter. Yet they laid a plan for plundering the party, and
would at the last perhaps have murdered the whole crew, had not Mr. Taylor
most adroitly and coolly foiled them in their designs.
All attempts to persuade his men to go farther were useless. No urging, no
promise of gifts, no threats would induce them to sail farther south, as they
believed that it was but a little way to “the end of the world.” How eagerly he
yearned for some chance to explore the country beyond, he often mentioned
in after life. He was at the centre of a mighty continent. Locked and bolted it
had been for all the ages, and it appeared as if the door was now open and
he had only to walk in to discover its treasures. But alas! he could not go on
alone. He could not swim the length of the river, nor find his way among the
elephants and lions of the jungle. The boat turned back toward Khartoum,
and he had no choice but to return with it.
However, he made the most of the trip, and frequently visited the shore and
had some very pleasant and instructive interviews with the tribes who live in
that region. At one place he visited a village of the Hassaniyehs, and contrary
to the experience of many other travellers, he was cordially invited to their
circle and treated with sincere hospitality. He mentioned in his book the dance
of welcome which the young women of the village performed before him, and
described with interesting detail their motions, features, forms, voices, and
habits. Thus, with visits to savages, interviews with wild beasts, and exquisite
views of the wildest scenery ever beheld by man, he floated back to the
friends and dwellings of Khartoum.
His stay in Khartoum, on his return, was brief, because of the approaching
sickly season; but every hour of his time, when awake, was occupied in
visiting and being visited. Native chiefs, Arab merchants, holy men of the
Moslem faith, Catholic priests, princesses, soldiers, consuls, boatmen, and
tame lions, seemed equally at home in his presence; and his stay was a most
delightful one for all concerned. His parting with his friends at Khartoum was
akin to the separation of life-long friends, or the breaking of a family circle. To
him the whole world was kin.
SCENE IN NORTH AFRICA.
—Taylor.
CHAPTER XX.
Departure from Egypt.—A Poet in Palestine.—Difference in Travellers.—Mr.
Taylor’s Appreciation.—First View of Tyre.—Route to Jerusalem.—The
Holy City.—Bath in the Dead Sea.—Appearance of Jerusalem.—
Samaria.—Looking down upon Damascus.—Life in the eldest City.—The
Bath.—Dose of Hashish.—Being a Turk among Turks.
—Taylor, 1852.
If there is any land where every grain of sand and every blade of grass is
pervaded by thrilling associations, that land is Palestine. Especially and
peculiarly animated are its hills and vales to a poet such as Taylor proved to
be. It may be that some superficial and matter-of-fact people who have
visited the Holy Land in the hot season, have not felt the charm of its
sacredness, owing to heat, barrenness, vermin, and beggars. There may be a
small class of iconoclastic jokers, who, caring not how holy or tender the
theme, never fail to use it for ridicule, if it suits their humoristic purpose. But
the large class of travellers who visit Jerusalem and the country round about,
feel the inspiring presence of the Past, and enjoy in an indescribable fullness
the associations connected with it. In a higher and nobler degree, the mind
imbued with poetic images, a ready imagination, and a keen discernment of
beauty in landscape or history, will avail itself of the great opportunities for
pleasure and profit which such a land supplies. In this sense Mr. Taylor
enjoyed a great advantage. He made his physical being so subordinate to his
mental, that no fatigue, no hunger, no thirst, no annoyance from beggars, nor
fears of robbers, could interfere with the appreciation of the beautiful. How
greatly he enjoyed his visit to Palestine, none but intimate friends ever knew.
In his letters, he often gave way to enthusiastic expressions, and in his book,
often gave very vivid descriptions of what had been, as well as that which
then existed. But a fear of exaggeration through praise, and a modest
misgiving lest his poetical fancy should not suit his readers, led him to write in
a more prosy vein than he talked. In conversation with friends in Germany
and America, and often in his lectures, after he had finished his tours, he
graphically pictured the impressive events of the past connected with
Palestine, which seemed to pass like a panorama before him. To him, such a
land would be full of interest, whether he trod its fields at a time of the year
when it was luxuriant, or at a season when the sun and simoon have made it
a desert. To lie upon its burning sands and dream of the sweltering hosts that
fought around the spot; to bask in the cool shades of its olives and cedars,
and think of Gethsemane and the sweets of Sharon; to stand on the summit
of the Mount of Olives, Carmel, or Hermon, and realize the almost
overwhelming fact that before him were the plains, hills, valleys, conquered
and reconquered since man was made, and which were peopled by the great,
the good, the wild, and the bloodthirsty of every age; to recognize the
localities where dwelt or fought the heroes of Holy Writ; to feel the presence
of the King of kings as “on mysterious wings” he swept the plain and shielded
his people; to walk on the very path whereon the Son of God had often
placed his feet; to dream in the starlight of Apostles, priests, Romans,
Crusaders, and Saracens, was an experience especially gratifying to him, and
interesting to a greater or less degree to all travellers. The writer recalls,
perhaps in an imperfect form, a verse which Mr. Taylor wrote during his stay
in Palestine, and which came to the writer with singular force while carelessly
wandering along the valley between Jerusalem and the Mount of Olives.
“Thy strength, Jerusalem, is o’er,
And broken are thy walls;
The harp of Israel sounds no more
In thy deserted halls:
But where thy Kings and Prophets trod,
Triumphant over death,
Behold the living soul of God,—
The Christ of Nazareth!
The halo of his presence fills
Thy courts, thy ways of men;
His footsteps on thy holy hills
Are beautiful as then;
The prayer, whose bloody sweat betrayed
His human agony,
Still haunts the awful olive-shade
Of old Gethsemane.”
To him the past was real. He saw the fields of corn, the ancient olive-trees,
the high walls, and the high towers, upon which the Saviour looked. He saw
again Abraham, Samuel, Saul, David, Isaiah, Jeremiah, Pilate, and their
associates. He walked in imagination in the welcoming crowd as they strewed
the branches along the path from Bethany to Jerusalem. He saw the council
chamber, the cross, and the ascension. He dreamed of the gathering armies
at Antioch and Joppa, whose banners at last waved over the palace of
Godfrey of Bouillon in Jerusalem. To him the gates of history swung wide
open, and he wandered back through the centuries, meeting patriarch and
maiden, shepherd and warrior, prophet and judge, seer and apostle, in a
companionship social and confidential. It was like long generations of
experience to walk those hallowed fields and realize the wonderful tales of
history. In this, as much as in the views of the present, is found the profit
resulting from travel in such lands. One lives over the tales of which he has
read, with each locality serving as a fresh reminder of the unnoted details. He
is an old man in experience who has travelled in the right spirit over those
eldest lands of the world; and few indeed is the number of tourists who can
feel that they have done so.
Mr. Taylor, like Longfellow, Tennyson, and Scott, had a gift of looking
through the present into the past, and held delightful communion with the old
days. Trying, however, with a laudable desire to instruct his readers, he kept
studiously close to the simple facts of his actual experience, and in his
narrative seldom allowed himself to fall into poetical expressions.
He left Egypt about the middle of the month of April and landed at Beyrout,
which was not at that time, nor since, a very attractive locality. It was made
more unpleasant to him by an incarceration in a kind of prison called the
“Quarantine.” But with a resignation worthy of the oldest Turk, he made the
best of his circumstances, and judging by the account he has given of it, he
had an easy, jolly time of it. Released from the prison he travelled down the
shore of the Mediterranean to Tyre, with whose remnant he seems to have
been deeply impressed. The old Tyre, with its fleets, with its enormous stocks
of merchandise, with its lofty piles of cedar timber, with its gorgeous purple
robes, with its bulwarks and battlements, with its armed defenders and hosts
of besiegers, arose from its crumbled fragments and passed through the
panoramic changes which so startle the student of Syrian history.
After leaving the village which now replaces the ancient city, he rode down
the sandy shore and composed a poem which was afterwards somewhat
changed, but in which was retained the boldness of the waves, which then
beat at his feet.
“The wild and windy morning is lit with lurid fire;
The thundering surf of ocean beats on the rocks of Tyre,—
Beats on the fallen columns and round the headland roars,
And hurls its foamy volume along the hollow shores,
And calls with angry clamor, that speaks its long desire:
‘Where are the ships of Tarshish, the mighty ships of Tyre?’
On the 7th of May he left Jerusalem, in company with another traveller and
the mule-drivers, taking the route by way of Samaria to Nazareth through a
country at that season covered with the richest and freshest foliage. Along the
entire route the tourist seldom passes out of sight of broken columns, falling
fortresses, gray old monasteries, dismal hermitages, and Roman masonry. The
olive and fig trees shaded the path, and with the wide fields of grain gave the
appearance of thrift and enterprise. He visited Shechem, where it is said that
Joseph was buried, and near which he was thrown into the pit by his
brethren. There Mr. Taylor saw Samaritans of the original stock, and there he
was shown an ancient manuscript of Hebrew Law, said to be three thousand
years old.
He made a short stop at Nazareth and was shown where the mother of
Christ had resided, the table from which Christ ate, and the school-room (?) in
which Christ is said to have been taught.
Going thence he ascended Mount Tabor, as it was his custom to climb all
the mountains he could reach, and then hastened on to the Sea of Galilee.
There he swam in its crystal water, and visited the Mount of Beatitudes,
Joseph’s Well, and Magadala, the home of Mary Magdalene. Passing Cesarea
Philippi, and crossing the anti-Lebanon range of mountains in imminent
danger of robbery and death from the rebellious tribes of Druses which
inhabited that region, they came out on the afternoon of May 19th in view of
the lovely city of Damascus.
Mr. Taylor made a sketch of himself as he appeared in his Eastern costume,
while seated on an eminence that afternoon, overlooking the most ancient
city in the world. In one of the rooms of Mr. Taylor’s lovely home of Cedarcroft
there hangs a large painting, of considerable merit, and said to be an
excellent portrait, which was executed by a friend from that sketch. It
represents Mr. Taylor sitting in Oriental posture, on the mountain-side, with
the domes, minarets, and embowered walls of Damascus on the distant plain.
He always held that painting to be a treasure, connecting him, as it did, with
those scenes of early travel, and with the friend who made the painting, and
with those who admired it.
He was delighted with Damascus. It was placed in the centre of a plain
whereon grew in the greatest abundance all the fruits and all the varieties of
leaf and blossom known to the tropic zone. No other spot yet explored can
boast such beautiful trees; such a profusion of roses; such blossoms of
jessamine and pomegranate; such loads of walnuts, figs, olives, apricots; such
luxuriant grasses, and such productive fields, as that land which has been
cultivated by man the longest. Nature has set the crown upon Damascus and
blessed it with a superabundance of vegetable life. But what is given to
verdure seems to be taken from humanity, for, regarded as a whole, he found
the people of the city to be a rather bad lot. Yet there, as elsewhere, he found
agreeable companions and warm friends. He made himself so much at home
that he soon appeared like a native, and all the labyrinths of bazars and alleys
were as familiar to him after a few days’ stay as they seemed to be to the
oldest resident. He liked their life so well that he soon learned to enjoy to its
full the physical comfort and mental rest of the Turkish bath. He ever after
referred to the bath at Damascus as the acme of bodily satisfaction. The fact
that so many travellers have been disappointed in the enjoyment of the bath
does not show Mr. Taylor’s account to be so much overdrawn, as it shows the
difference between the pleasure to be derived from the pastimes of any
people by those who adhere more or less to their own tastes and customs,
and those who, like Mr. Taylor, fall wholly and heartily into the ways and
thoughts of the native. When in Damascus, he not only did as they do
outwardly, but he set his mind in the same channel, and knew what it was to
be a Turk in aspirations as well as in dress. No other traveller known to
literature ever entered so completely into the experience and social
companionship of the people whom he visited.
In order that he might leave no habit untried which came within his reach,
he took a potion of hashish, to test its strength and effects. The drug did not
begin to intoxicate him quite as soon as he expected, and he doubled the
dose, thus taking six times as much as would intoxicate an ordinary Turk. It
made him terribly ill; and it was almost miraculous that he survived the shock
to his system. He did not try the strength of that drug again. Among the
friends he made, and whose home he visited at Damascus, was a family of
Maronite Christians, who, eight years later, were heinously butchered by the
Moslems during the great massacre following the Druses’ and Marnoites’
dispute in 1860.
CHAPTER XXI.
Leaving Damascus.—Arrival at Beyrout.—Trip to Aleppo.—Enters Asia Minor.
—The Scenery and People.—The Hills of Lebanon.—Beautiful Scenes
about Brousa.—Enters Constantinople.—A Prophesy.—Return to
Smyrna.—Again in Italy.—Visits his German Friend at Gotha.—The
Home of his Second Love.—Goes to London.—Visits Gibraltar.—Cadiz.—
Seville.—Spanish History.
From Damascus Mr. Taylor journeyed to Baalbec, where are the most
imposing ruins to be found in Syria, and where stand six of the most
symmetrical and exquisitely carved columns to be seen in Asia or Europe. He
described the temples and fragments so vividly, that travellers who have taken
his “Lands of the Saracen” for a guide have seldom been disappointed or
mistaken in their anticipations, the actual scene they look upon being so like
the image they formed in their minds while reading his description. The gift of
portraying through the combination of words and sentences an accurate
picture of a city existing in a strange land and amid a strange people, is a rare
gift, and the number is very few of those who are found to possess it. Mr.
Taylor was one of those privileged ones. In his description we see the
columns, cornices, pediments, walls, platforms, broken pillars, and falling
pavilions as distinctly as they appear when we afterwards look upon those
romantic piles with the natural eye. To him, as to others, it was a study to
determine, if possible, how such enormous blocks of stone, sixty-two feet long
and ten feet in diameter, could have been transported and placed in the
buildings. It is beyond all the skill of to-day to move nine thousand tons of
stone in a single block with the conveniences of that time.
From Baalbec he ascended the Lebanon range of mountains, and looked
over the land from the snowy peak of one of its lofty summits. He visited the
sacred cedars which have lived on the mountain-side for three thousand
years, and then rode on through chasms, along cliffs, and by the sweetest
and richest dells, until he descended to the plain of Beyrout.
His appreciation of the hills of Lebanon is more clearly seen in his poetry
than in his prose. For, when writing of them afterwards, he said:—
In that city he laid his plans for the future, and abandoned his purposed trip
to the Euphrates and Tigris. He relinquished the design to visit Assyria with
great reluctance, and decided to pass through the interior of Asia Minor to
Constantinople. Acting immediately upon this resolution, without an apparent
doubt of being able to traverse safely the unknown interior of Asia Minor, he
engaged a vessel and sailed up the coast to the Orontes River, and thence to
Aleppo. In that city, by a ludicrous mistake, Mr. Taylor and his travelling
companion were invited to the house of one of the wealthiest merchants, and
were treated with the greatest hospitality by the owner, who supposed they
were titled Englishmen. But when the mistake was revealed, Mr. Taylor had
become such an agreeable visitor that his host insisted upon entertaining
them during their stay in Aleppo. He had been there but a few days before he
became such a general favorite, that he was invited to call on the nobility, was
urged to attend feasts, balls, and weddings, and when he left the city, the
friendly regrets of hundreds of Moslems and Christians followed him.
Leaving Aleppo early in June, he followed the shore of the Mediterranean
around to the plain of Issus, where Alexander the Great won his great victory,
and thence to Tarsus, the birthplace of the Apostle Paul. It may have been “no
mean city” when Paul was born, but it was a most insignificant village when
Mr. Taylor was there. But as the magnificent mountains of the Taurus range
loomed up along the northern horizon, his attention was taken from rags,
beggary, and ruined fortresses, to snowy cliffs, over which he had a passion
for clambering.
Those persons who have ascended the Alps at the Simplon pass, have a
very good idea of the Taurus mountains, and can realize somewhat of Mr.
Taylor’s satisfaction as he rode up the gorges and peered into the deep
valleys. He loved the mountains anywhere. But the Taurus seemed then, in
the glow of his return to perfect health and with all the profusion of nature’s
living beauties blooming about him, and the eternal snows gleaming above
him, to be the most attractive landscape in the world.
His visit to Konia (Iconium), the capital of Karamania, was full of little
episodes and personal incidents, which he told afterwards in print in his own
inimitable manner. But nothing of unusual moment occurred until he reached
ancient Phrygia, where the ruins of olden cities and fortresses interested him
much. Their history was almost as unknown as the story of the temples of
Yucatan, and consequently had a mysterious appearance which charms in a
bewildering way the study of a poet.
Riding on over hills and mountains, across delightful streams, through
fertile valleys, associating with the Turks on friendly terms, and studying their
habits and language, Mr. Taylor pushed fearlessly into the very heart of Asia
Minor. Visiting Oezani in its debris, and the valley of Rhyndacus, they
traversed the primeval forests on the Mysian Olympus, and true to his
instincts he sought the heights of Olympus, twin mountain, in size and
literature, with its Grecian namesake. From that point to Brousa, near the Sea
of Marmora, it was but a day’s journey, and seems to have been the most
delightful ride of the whole tour. Gardens, orchards, grain-fields, thickets of
clematis and roses, patches of beech and oak woodland, and brilliant streams
pleased the eye, while the songs of birds and of happy harvesters charmed
the ear. Grand mountains pierced the skies, covered with dense forests,
behind them, and the plain stretched away—a Garden of Eden—to the shore
of a placid inland sea.
They entered Brousa in excellent health and spirits, having seen no unusual
fatigue and been in no great danger during the whole journey through a
country then almost lost and unknown to the civilized world.
From Brousa, the party descended to the Sea of Marmora, and taking a sail-
boat were wafted by the Golden Horn into the interminable fleets of
Constantinople. During his stay in that city he witnessed the display of the
Turkish holidays, saw the Sultan on his throne, entered the mosque of Saint
Sophia, ran to the numerous conflagrations, and unravelled to his satisfaction
some of the social and political problems connected with the Sultan’s rule and
the state of popular discontent. He foretold a war with Russia, and a contest
between the latter and England over the coveted gem of the East and the
gate to the Black Sea. His predictions have already been proven to be true,
showing an insight into political affairs wholly unlooked for in a young man,
and not to be found in such as had travelled to less purpose.
On leaving Constantinople, he proceeded again to Smyrna, which place
appeared to so much better advantage on his second visit than it did at his
first, that instead of leaving it, as before, with anathemas, he celebrated his
visit with a poem.
The reader may not need to be again reminded of Mr. Taylor’s double view
of the scenes he visited, or of the fact that he tried to give faithful pictures of
the present in his prose and left the ideal and fanciful to his books of poetry.
But to understand his disposition, and correctly estimate his ability, they need
to be read together; and hence, before taking leave of Asia Minor, we venture
to quote a verse from a dedication to his friend Richard H. Stoddard, which
we have seen in a volume of Mr. Taylor’s poems.
“O Friend, were you but couched on Tmolus’ side,
In the warm myrtles, in the golden air
Of the declining day, which half lays bare,
Half drapes, the silent mountains and the wide
Embosomed vale, that wanders to the sea;
And the far sea, with doubtful specks of sail,
And farthest isles, that slumber tranquilly
Beneath the Ionian autumn’s violet veil;—
Were you but with me, little were the need
Of this imperfect artifice of rhyme,
Where the strong Fancy peals a broken chime
And the ripe brain but sheds abortive seed.
But I am solitary, and the curse,
Or blessing, which has clung to me from birth—
The torment and the ecstasy of verse—
Comes up to me from the illustrious earth
Of ancient Tmolus; and the very stones,
Reverberant, din the mellow air with tones
Winch the sweet air remembers; and they blend
With fainter echoes, which the mountains fling
From far oracular caverns: so, my Friend,
I cannot choose but sing.”
At Constantinople Mr. Taylor heard of the action which had been taken by
the United States, looking to the opening of the ports of Japan to the
commerce of America. He heard that a squadron was to leave the United
States in November, under the command of Commodore Perry, and he formed
the resolution to connect himself with the expedition, if possible. To that end
he wrote to his friends and employers in New York, asking them to obtain
permission for him to join the fleet. Not knowing just when the expedition
would sail, nor at what ports it would stop on its way to Japan, he anxiously
watched for information, and inquired at every place where information was
likely to be found.
He was determined to visit Spain before he went to China and Japan, and
was equally resolved to visit the home of his German travelling companion
who ascended the Nile with him, and who had sent pressing invitations to him
to come to Gotha.
The business details connected with his finances and outfit for Spain and
China also called him to London, and arranging his tour so as to accomplish
these diverse ends he visited Malta, where he was delayed ten days, and then
sailed to Sicily, where he witnessed the Catanian centennial festival in honor
of St. Agatha, and where he beheld the awful spectacle of Ætna in eruption.
From Sicily he sailed up the coast to that Naples which, as a wayfarer in Rome
seven years before, he had so much longed to see, and filled his letters with
praises of its beautiful bay and charming circle of mountain, city, town, cliffs,
and islands. Without changing steamers he proceeded to Leghorn, and going
to Florence experienced that delight of all delights,—in Florence a second
time. Feeling that his time was limited, and “drawn by an unseen influence,”
he hastened on to Venice, and thence through the regions of the Austrian
Tyrol to Munich and Gotha.
Gladsome days at Gotha! Was it not the country of his beloved friend? Was
it not the home of his friend’s niece, Marie Hansen? The daughter of the great
astronomer, Peter Andreas Hansen, was a worthy child of a noble sire. Mr.
Taylor had listened to her praises, but had hardly hoped to meet her.
—Taylor’s Deukalion.
After a few weeks spent in and about that pleasant city, to which he was
destined to return and claim his bride, and in which he was to pass many of
the sweetest days of his life, he journeyed to London. There he made his
arrangements for a trip into China, and hastened away to Gibraltar.
On the 6th of November he left the great rock and took passage in a
steamer for Cadiz, in Spain. There he walked the streets three thousand years
old, and wherein, it is said, that Hercules strode. Yet there is but little now to
be seen that would remind one of antiquity. He noticed, however, the
beautiful and graceful women. From Cadiz he went by boat up the
Guadalquiver River to the pretty town of Seville. There were the old Moorish
houses; there the massive Cathedral; there the Saracenic palace of Alcazar,
with all its porches, galleries, arches, and sculptures; there was the palace
called Pilate’s House, with its decorations from Arabia, and inscriptions from
the Koran; and there was the museum containing Murillo’s best paintings.
But it requires only a short time to visit all the attractions of Seville, and Mr.
Taylor soon proceeded to Granada. In nearly all the cities which he visited he
was reminded, directly or indirectly, of the visit of his friend, Washington
Irving. He found the same guides, or lodged at the same hotel, or visited
some celebrated locality of which Irving had written.
In Granada was the celebrated fortress of Alhambra, which was captured
from the Moors by the troops of Ferdinand and Isabella the same year that
Columbus discovered America; there was the palace of Charles V.; there the
Carthusian convent, the Monastery of St. Geronimo, and there the cathedral
with the remains of Ferdinand and Isabella. He made a hasty trip to Cordova
and its ancient Moslem mosque. Then, visiting Alhama, Malaga, and Ronda,
he returned hastily to Gibraltar and examined the renowned fortress, said to
be the strongest citadel in the world.
In that somewhat hasty view of Southern Spain he obtained much valuable
information and an experience which often served him in his literary work as a
writer for the public press. Southern Spain and Southern France, next to
Rome itself, are replete with warlike and romantic associations. Gauls,
Romans, Moors, and Spaniards, have made nearly every plain a battle-field;
and the toppling walls of the ancient towers and palaces tell of the fiercest
contests, the most terrible inquisitions, and the narrowest of narrow escapes.
Song and story in prose and rhyme have combined in every form to make the
land attractive, and it is a matter of deep regret that Mr. Taylor, who was so
capable of developing all these characteristics, had not more time in which to
visit them and write out his experience.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com